sam*_*am -1 python regex python-2.7
if __name__ == '__main__':
filename = open('sevi.txt', 'wb')
content = filename.write("Cats are smarter than dogs")
for line in content.read():
match = re.findall('[A-Z]+', line)
print match
filename.close()
Run Code Online (Sandbox Code Playgroud)
我是python的新手.我只是打开一个文件并在其中写入一些文本.稍后阅读内容通过使用正则表达式查找其中的所有字符.但我收到错误,因为'NoneType'对象没有属性'read'.如果我也使用readlines,我收到错误.
该file.write()
方法None
在Python 2中返回(在Python 3中,它返回为二进制文件写入的字节数).
如果您想要使用相同的文件进行写入和读取,则需要在w+
模式下打开该文件,然后回头将文件位置放回到开头:
with open('sevi.txt', 'w+b') as fileobj:
fileobj.write("Cats are smarter than dogs")
fileobj.seek(0) # move back to the start
for line in fileobj:
match = re.findall('[A-Z]+', line)
print match
Run Code Online (Sandbox Code Playgroud)
请注意,可以直接在文件对象上循环,生成单独的行.
我做了两个其他更改:我将您的变量重命名为fileobj
; 你有一个文件对象,而不仅仅是这里的文件名.我使用文件对象作为上下文管理器,因此即使块中发生任何错误,它也会自动关闭.