Python 如何读取/打印(_io.TextIOWrapper)数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43438303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read/print the ( _io.TextIOWrapper) data?
提问by everestial007
With the following code I want to > open a file > read the contents and strip the non-required lines > then write the data to the file and also read the file for downstream analyses.
使用以下代码,我想 > 打开文件 > 读取内容并去除不需要的行 > 然后将数据写入文件并读取文件以进行下游分析。
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()
Now, I want to read the f2 data and do further processing in pandas or other modules but I am running into a problem while reading the data(f2
).
现在,我想读取 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
回答by abccd
The file is already closed (when the previous with
block finishes), so you cannot do anything more to the file. To reopen the file, create another with statement and use the read
attribute to read the file.
该文件已关闭(当前一个with
块完成时),因此您无法对该文件执行任何操作。要重新打开文件,请创建另一个 with 语句并使用该read
属性读取文件。
with open('test_output.txt', 'r') as f2:
data = f2.read()
print(data)