Searching for a pattern in a text file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Searching for a pattern in a text file

Does anybody know why it's not working? file= open("Source_text.txt", "r") pattern1= r'[A-Z][a-z]+' match= re.findall(pattern1,file) I have error that findall expects string or bytes-like object. But when I copy the content from the file directly to the code and assign it to a variable then it works e.g. file= "This is a content of a file." pattern1= r'[A-Z][a-z]+' match= re.findall(pattern1,file) How can I find the pattern without copy the content to code?

15th Apr 2020, 10:47 PM
Ewelina Kowalik
Ewelina Kowalik - avatar
1 Answer
+ 2
You have to read the file into a var first and pass that into findall() pattern = r'[A-Z][a-z]+' with open ("Source_text.txt", "r") as f: data = f.read() match = re.findall(pattern, data, re.M) # re.M is for multiple lines omit if not needed
16th Apr 2020, 3:04 AM
ChaoticDawg
ChaoticDawg - avatar