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

102,030

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)
Share:
102,030
everestial007
Author by

everestial007

Evolution and Genomics Scientist with skills of a programmer and rustic hobbyist as a ping ponger and guitar player !

Updated on July 06, 2021

Comments

  • everestial007
    everestial007 almost 3 years

    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
    
  • everestial007
    everestial007 about 7 years
    I tried not putting f2.close() at the end of that for loop, but it didn't work either. I already know what you have suggested. I just didn't wanted to read the file again and again. Was wondering if that codes is missing something.
  • martineau
    martineau about 7 years
    @everestial007: The f2.close() is redundant because the preceding with does it automatically.
  • Leevo
    Leevo almost 5 years
    How can I convert f2 to an str object ?
  • Taku
    Taku almost 5 years
    @Leevo data is the str object of the file’s content.
  • Ivailo Bardarov
    Ivailo Bardarov almost 3 years
    @abccd how this answer is using io.TextIOWrapper ?
  • nlhnt
    nlhnt over 2 years
    Well the person asking forgot to read from the file handler. So he was trying to read using the wrong object.