Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 207
everestial007 Avatar asked Apr 16 '17 14:04

everestial007


People also ask

How do I read a TextIOWrapper file in Python?

TextIOWrapper class The file object returned by open() function is an object of type _io. TextIOWrapper . The class _io. TextIOWrapper provides methods and attributes which helps us to read or write data to and from the file.

What is _IO TextIOWrapper in Python?

TextIOWrapper , which extends TextIOBase , is a buffered text interface to a buffered raw stream ( BufferedIOBase ). Finally, StringIO is an in-memory stream for text.

What does TypeError '_ Io TextIOWrapper object is not callable mean?

The Python: "TypeError: '_io. TextIOWrapper' object is not callable" occurs when we try to call a file object as if it were a function. To solve the error, make sure you don't have any clashes between function and variable names and access properties on the file object instead.

What is file stream Python?

The file object is a data stream that supports next() method to read file line by line. When end of file is encountered, StopIteration exception is raised. f=open("python.txt","r") while True: try: line=next(f) print (line, end="") except StopIteration: break f.close()


1 Answers

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)
like image 195
Taku Avatar answered Oct 23 '22 17:10

Taku