I want to print the output of two regexs run against the same file.
I have tried
import re with open("C:\Users\frankDocuments\file-with-digits.txt") as myfile: print(re.findall(r'organizationID as ints*=s*(d+)', myfile.read())) print(re.findall(r'organizationIDs*=s*(d+)', myfile.read()))
and
import re with open("C:\Users\frankDocuments\file-with-digits.txt") as myfile: print(((re.findall(r'organizationID as ints*=s*(d+)', myfile.read())), re.findall(r'organizationIDs*=s*(d+)', myfile.read())))
In each case the second print statement shows no output.
If I run them separately they both show their unique output. How do I combine them so I see the output of both regular expressions? I can open the file twice of course and run them separately but I am thinking it must be possible to combine them.
Advertisement
Answer
This should answer your question: Why can’t I call read() twice on an open file?
In your specific case, what you want to do is:
import re with open("C:\Users\frankDocuments\file-with-digits.txt") as myfile: file_contents = myfile.read() print(re.findall(r'organizationID as ints*=s*(d+)', file_contents )) print(re.findall(r'organizationIDs*=s*(d+)', file_contents ))
Also, as a rule of thumb: I/O-operations like reading a file are generally slow. So even if calling read()
on a file twice had the effect you expected, it would be a good idea to do it just once and store the result in a variable, so you can re-use it.