0

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
3
  • file.readlines() returns list of string, re.findall() requires a string. Commented Mar 30, 2014 at 19:24
  • Moreover, you're specifying a list instead of a string. Commented Mar 30, 2014 at 19:26
  • @devnull indentation is not a problem here: the file is read and then closed. Commented Mar 30, 2014 at 19:27

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.