How to read/print the ( _io.TextIOWrapper) data?

everestial007 picture everestial007 · Apr 16, 2017 · Viewed 58.3k times · Source

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).

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

Answer

abccd picture abccd · Apr 16, 2017

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 open('test_output.txt', 'r') as f2:
    data = f2.read()
    print(data)