PythonのTypeError: '_ io.TextIOWrapper'オブジェクトは、/ readlines()/ with ... as ...を解決するためのサブスクリプト可能な問題ではありません。



Typeerror Python _io



readlines()の役割

file_name = '/Users/.../test.txt' with open(file_name,'r', encoding='utf-8') as fin: a = fin[1] # fin's second line of data Traceback (most recent call last): File '', line 4, in <module> a = fin[1] TypeError: '_io.TextIOWrapper' object is not subscriptable

TypeError:「_ io.TextIOWrapper」オブジェクトは下付き文字ではありません。ファイルに下付き文字でインデックスを付けることができないことを示します。正常に実行されるように、次のようにコードを修正します。

file_name = '/Users/.../test.txt' with open(file_name,'r', encoding='utf-8') as fin: a = fin.readlines()[1]

.readlines()は、ファイルの内容全体を各行で読み取り、読み取った内容をリストに入れて、リストタイプを返します。 .read()に関する詳細説明



と...として...

withステートメントは、コンテキストによって生成された例外を自動的に処理し、ファイルハンドルを閉じます。例は次のとおりです。

file_name = '/Users/hyacinth/Desktop/irgan-master/ltr-gan/ltr-gan-pointwise/MQ2008-semi/test.txt' with open(file_name,'r', encoding='utf-8') as fin: a = fin.readlines()[1] b=fin.readlines()[2] Traceback (most recent call last): File '', line 6, in <module> b=fin.readlines()[2] ValueError: I/O operation on closed file.

finファイルが閉じられました。 withのネストにない場合、I / Oは閉じたファイルに対して動作し、エラーValueError:閉じたファイルに対するI / O操作を報告します。 詳細:使用法と原則を備えたPython