gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:27:16 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com