0

I have a Python Script in which I'm opening two files for reading and when I'm trying to close them, it throws me the AttributeError: 'list' object has no attribute 'close' error.

Excerpt of my script is as below :

firstFile = open(jobname, 'r').readlines()  
secondFile = open(filename, 'r').readlines()  
{  
    bunch of logic  
}  
firstFile.close()  
secondFile.close()
4

4 に答える 4

9

firstFilesecondFile実際のファイルを表すものではなく、行のリストです。これを修正するには、ファイル ハンドルを保存します。

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

# bunch of logic ...

firstFile.close()  
secondFile.close()  

withまたは、次の構成を使用できます。

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

    # bunch of logic...
于 2013-10-15T15:08:22.590 に答える
5

.readlines()リストを返します。あなたは実際に次のようなことをしたいと思うでしょう:

with open(jobname) as first, open(filename) as second:
    first_lines = first.readlines()
    second_lines = second.readlines()

このwithブロックは、ファイル ハンドルのクローズとクリーンアップを自動的に処理します。

また、実際にファイルの内容全体をメモリに格納したい場合を除き、おそらくreadlines は実際には必要ありません。ファイル自体を直接反復処理できます。

for line in first:
    #do stuff with line

または、それらが同じ長さの場合:

for line_one, line_two in zip(first, second):
    # do things with line_one and line_two
于 2013-10-15T15:09:36.053 に答える
3

他のケースは正しいですが、自動リソース管理を使用することもできます:

with open(jobname, 'r') as f:
    first_file_lines = f.readlines()
with open(filename, 'r') as f:
    second_file_lines = f.readlines()

# your logic on first_file_lines and second_file_lines here

すべての行を読んだ後も、ファイルを開いたままにしておく必要はありません。

于 2013-10-15T15:11:40.937 に答える
1

でファイル オブジェクトを作成した直後にメソッドopenを呼び出すとreadlines()、その結果が変数にバインドされます。つまり、firstfileファイルではなく文字列のリスト (ファイルの行) であり、実際のファイルへの参照は失われます。 . についても同じですsecondFile。代わりにこれを試してください:

firstFile = open(jobname, 'r')
lines = firstFile.readlines()  
...
firstFile.close()
于 2013-10-15T15:08:06.863 に答える