Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert _io.TextIOWrapper to string?

I read the text format using below code,

f = open("document.txt", "r+", encoding='utf-8-sig')
f.read()

But the type of f is _io.TextIOWrapper. But I need type as string to move on.

Please help me to convert _io.TextIOWrapper to string.

like image 762
BSP Avatar asked Jun 26 '20 07:06

BSP


People also ask

What is _IO TextIOWrapper 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 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.


1 Answers

You need to use the output of f.read().

string = f.read()

I think your confusion is that f will be turned into a string just by calling its method .read(), but that's not the case. I don't think it's even possible for builtins to do that.

For reference, _io.TextIOWrapper is the class of an open text file. See the documentation for io.TextIOWrapper.


By the way, best practice is to use a with-statement for opening files:

with open("document.txt", "r", encoding='utf-8-sig') as f:
    string = f.read()
like image 173
wjandrea Avatar answered Sep 22 '22 16:09

wjandrea