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

标签 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()

现在,我想读取 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 block 结束时),所以您不能再对文件做任何事情。要重新打开文件,请创建另一个 with 语句并使用 read 属性读取文件。

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

关于python - 如何读取/打印(_io.TextIOWrapper)数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43438303/

相关文章:

c# - 在这个相对简单的程序中得到 'out of memory' 异常

python字符串连接混淆

python - 导入错误 : cannot import name 'BeautifulSoup' , bs4 已安装

javascript - window.print() 在 IE 中不工作

arrays - 在 Excel 中打印特定工作表,具有不同的打印区域和使用 VBA 的打印设置

ruby - 如何在 Ruby 中使用 Open#popen3 读取无缓冲的标准输出

java - 在Java中部分读取文件

python - 如何在整个项目中共享类的实例?

Python:防止savefig覆盖旧图

c - 在 C 中输出的开头打印一个额外的空行