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

问题描述:

用下面的代码我想>打开文件>读取内容并去掉非必需的行>然后将数据写入文件并读取文件以进行下游分析。如何读取/打印(_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数据和大熊猫或其他模块做进一步的处理,但我遇到了一个问题,同时读取数据(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 
+0

请问您能具体吗?我尝试在代码的第二行执行'f2.read()',同时打开(...)为f2.read()',但它不起作用。 – everestial007

文件已关闭(在前面的with块结束),所以你不能做任何更多的文件。要重新打开文件,请创建另一个语句并使用read属性读取文件。

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

我试着不把'f2.close()'放在for循环的末尾,但它也不起作用。我已经知道你有什么建议。我只是不想一次又一次地读取文件。想知道这些代码是否缺少一些东西。 – everestial007

+0

您必须关闭文件才能保存文件,重新打开它就是* only * *方式。当块结束时,你的'with'块将会自动关闭文件。无论是否添加.close()或不是 – abccd

+1

@ everestial007:'f2.close()'是多余的,因为前面的'with'会自动完成。 – martineau