如何read/print(_io.TextIOWrapper)数据?

How to read/print the ( _io.TextIOWrapper) data?

我想使用以下代码 > 打开文件 > 读取内容并删除不需要的行 > 然后将数据写入文件并读取文件以供下游分析。

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

该文件已经关闭(当前一个 with 块完成时),因此您无法对该文件做任何更多的事情。要重新打开文件,请创建另一个 with 语句并使用 read 属性读取文件。

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