如何读取/打印(_io.TextIOWrapper)数据?

eve*_*007 16 python printing io typeerror word-wrap

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

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()
Run Code Online (Sandbox Code Playgroud)

现在,我想读取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
Run Code Online (Sandbox Code Playgroud)

abc*_*ccd 24

该文件已关闭(上一个with块完成时),因此您无法对该文件执行任何操作.要重新打开该文件,请创建另一个with语句并使用该read属性读取该文件.

with open('test_output.txt', 'r') as f2:
    data = f2.read()
    print(data)
Run Code Online (Sandbox Code Playgroud)

  • @ everestial007:f2.close()是多余的,因为前面的with会自动执行。 (5认同)