BSP
BSP

Reputation: 422

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.

Upvotes: 19

Views: 60048

Answers (3)

ben othman zied
ben othman zied

Reputation: 310

This is good:

with open(file, 'r', encoding='utf-8-sig') as f:
    data = f.read()

This is not good:

with open(file, 'r', encoding='utf-8-sig') as file:
    data = file.read()

Upvotes: -4

wjandrea
wjandrea

Reputation: 33062

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

Upvotes: 23

PixelatedStarfish
PixelatedStarfish

Reputation: 7

It's not a super elegant solution but it works for me

def extractPath(innie):
    iggy = str(innie)

    getridofme ="<_io.TextIOWrapper name='"
    getridofmetoo ="' mode='r' encoding='UTF-8'>"

    iggy = iggy.replace(getridofme, "")
    iggy = iggy.replace(getridofmetoo, "")
    #iggy.trim()

    print(iggy)

    return iggy

Upvotes: -5

Related Questions