为什么这段代码会给我一个错误?

时间:2014-03-30 19:22:57

标签: python python-2.7 python-3.x

我有这段代码:

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))

运行时,它应该找到所有三位数字,然后将它们打印到新的文本文件中。

当我运行它时,我收到此错误:

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

我做错了什么?

1 个答案:

答案 0 :(得分:4)

re.findall期望字符串作为其第二个参数,但文件对象的readlines方法返回一个列表。也许您打算使用read方法(返回一个字符串):

with open("text2.txt", "r") as f:
    content = f.read()