'_io.TextIOWrapper' object is not callable is appearing on one code, but not on the other

Viewed 18

So i was writing in jupyter notebook the code:

txtpath='C:\\Users\\Desktop\\somefile.txt'
q=open(txtpath)
print(q.read())

and it turns out okay. but when I try the same code (literally copy and paste) on another tab of jupyter notebook, it returns:

'_io.TextIOWrapper' object is not callable

I was wondering why this is happening? Thanks!

1 Answers

It appears as though you may have opened the file without closing it.

A safer way of opening files is like this:

txtpath='C:\\Users\\Desktop\\somefile.txt'

# this guarantees that the file closes
with open(txtpath, 'r') as f:
    data = f.read()

print(data)

The with statement guarantees the closure, so you dont have to remember close().

Related