I have this code:
import re
with open("text2.txt", "r") as f:
content = f.readlines()
numbers = re.findall(r'\b\d{3}\b', content)
with open("text3.txt", "w") as f:
f.write(str(numbers))
When run, it's supposed to find all of the three digit numbers, and print them to a new text file.
When I run it, I get this error:
Traceback (most recent call last):
File "C:\Users\Zach\Desktop\test3.py", line 4, in <module>
numbers = re.findall(r'\b\d{3}\b', content)
File "C:\Panda3D-1.7.2\python\lib\re.py", line 177, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
What am I doing wrong?
asked Mar 30, 2014 at 19:22
Zach Gates
2833 gold badges5 silver badges11 bronze badges
1 Answer 1
re.findall expects a string as its second argument, but the readlines method of a file object returns a list. Perhaps you meant to use the read method instead (which returns a string):
with open("text2.txt", "r") as f:
content = f.read()
answered Mar 30, 2014 at 19:25
user2555451
Sign up to request clarification or add additional context in comments.
Comments
lang-py
file.readlines()returns list of string,re.findall()requires a string.