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
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.
TextIOWrapper , which extends TextIOBase , is a buffered text interface to a buffered raw stream ( BufferedIOBase ). Finally, StringIO is an in-memory stream for text.
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.
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()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With