![](/img/trans.png)
[英]python - AttributeError: 'NoneType' object has no attribute 'read'
[英]AttributeError: 'NoneType' object has no attribute 'read' in python
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()
我是python的新手。 我只是打开一个文件并向其中写入一些文本。 稍后阅读内容时,可以使用正则表达式查找其中的所有字符。 但是我收到错误消息,因为“ NoneType”对象没有属性“ read”。 如果我也使用readlines,则会收到错误消息。
file.write()
方法在Python 2中返回None
(在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
请注意,可以直接完成文件对象的循环,从而产生单独的行。
我进行了另外两项更改:我将您的变量重命名为fileobj
; 您有一个文件对象,而不仅仅是这里的文件名。 而且我使用了文件对象作为上下文管理器,这样即使在块中发生任何错误,它也会自动关闭。
filename.write("Cats are smarter than dogs")
是一个返回None
类型的函数,就像Python中的每个函数一样,如果未通过return
语句另外指定的话。 因此,变量content
值为None
,您正在尝试从中读取值。 尝试使用filename.read()
代替。
import re
ofile = open('sevi.txt', 'r+')
ofile.write("Cats are smarter than dogs")
ofile.seek(0)
data = ofile.read()
upper = re.findall(r'[A-Z]', data)
print upper
lower = re.findall(r'[a-z]', data)
print lower
ofile.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.