AttributeError:'NoneType'对象在python中没有属性'read'

时间:2016-02-17 12:55:11

标签: 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()

我是python的新手。我只是打开一个文件并在其中写入一些文本。稍后阅读内容通过使用正则表达式查找其中的所有字符。但我收到错误,因为'NoneType'对象没有属性'read'。如果我也使用readlines,我收到错误。

3 个答案:

答案 0 :(得分:6)

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;你有一个文件对象,而不仅仅是这里的文件名。我使用文件对象作为上下文管理器,因此即使块中发生任何错误,它也会自动关闭。

答案 1 :(得分:0)

filename.write("Cats are smarter than dogs")是一个返回None类型的函数,就像Python中的每个函数一样,如果没有用return语句指定的话。因此,变量content的值为None,您正试图从中读取。请改为filename.read()

答案 2 :(得分:0)

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