AttributeError:'list'对象没有属性'close'

use*_*260 0 python

我有一个Python脚本,其中我打开两个文件进行读取,当我试图关闭它们时,它会抛出AttributeError:'list'对象没有属性'close'错误.

我的脚本摘录如下:

firstFile = open(jobname, 'r').readlines()  
secondFile = open(filename, 'r').readlines()  
{  
    bunch of logic  
}  
firstFile.close()  
secondFile.close()
Run Code Online (Sandbox Code Playgroud)

Mat*_*ant 9

firstFile并且secondFile不代表实际文件,它们是行列表.要解决此问题,请保存文件句柄.

firstFile = open(jobname, 'r')
firstFileData = firstFile.readlines()  
secondFile = open(filename, 'r')
secondFileData = secondFile.readlines()  

# bunch of logic ...

firstFile.close()  
secondFile.close()  
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用with构造:

with open(jobname, 'r'), open(filename, 'r') as firstFile, secondFile:
    firstFileData = firstFile.readlines()  
    secondFileData = secondFile.readlines()  

    # bunch of logic...
Run Code Online (Sandbox Code Playgroud)


Way*_*ner 5

.readlines()返回一个列表.你真的想做这样的事情:

with open(jobname) as first, open(filename) as second:
    first_lines = first.readlines()
    second_lines = second.readlines()
Run Code Online (Sandbox Code Playgroud)

with块将自动处理关闭和清理文件句柄.

此外,您可能实际上并不需要readlines,除非您确实希望文件的全部内容都在内存中.您可以直接遍历文件本身:

for line in first:
    #do stuff with line
Run Code Online (Sandbox Code Playgroud)

或者如果它们的长度相同:

for line_one, line_two in zip(first, second):
    # do things with line_one and line_two
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在Python 2中,`zip`会将两个文件读入内存以构造对列表. (2认同)