web-dev-qa-db-ja.com

(_io.TextIOWrapper)データの読み取り/印刷方法は?

次のコードでは、ファイルを開き、内容を読み取り、不要な行を削除し、データをファイルに書き込み、さらに下流の分析のためにファイルを読み取ります。

with open("chr2_head25.gtf", 'r') as f,\
    open('test_output.txt', 'w+') as f2:
    for lines in f:
        if not lines.startswith('#'):
            f2.write(lines)
    f2.close()

ここで、f2データを読み取り、pandasまたは他のモジュールでさらに処理を行いたいが、データの読み取り中に問題が発生している(f2)。

data = f2 # doesn't work
print(data) #gives
<_io.TextIOWrapper name='test_output.txt' mode='w+' encoding='UTF-8'>

data = io.StringIO(f2)  # doesn't work
# Error message
Traceback (most recent call last):
  File "/home/everestial007/PycharmProjects/stitcher/pHASE-Stitcher-Markov/markov_final_test/phase_to_vcf.py", line 64, in <module>
data = io.StringIO(f2)
TypeError: initial_value must be str or None, not _io.TextIOWrapper
13
everestial007

ファイルは既に閉じられているため(前のwithブロックが終了したとき)、ファイルに対してこれ以上何もすることはできません。ファイルを再度開くには、別のwithステートメントを作成し、read属性を使用してファイルを読み取ります。

with open('test_output.txt', 'r') as f2:
    data = f2.read()
    print(data)
21
abccd