简体   繁体   中英

How to resolve TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I create a gui using python tkinter. I got stuck at a point where i want to open a text file and then store the data of file into a list. I tried the following code:

root = Tk()
def open_f(): 
    global file
    file = askopenfile(mode ='rb', filetypes =[('All Files','*.*'),
                  ('pdf files', '*.pdf'),('txt Files','*.txt')])
    print('Selected:', file)
    
button1 = Button(root, text ="Select text file",command=open_f)
button1.grid(row=9,column=1,pady=5)
l1=[] 
TextFile = file
# open the file for data processing
with open(TextFile,encoding="utf8") as IpFile:
    for j in IpFile:
        l1.append(str(j).strip())   
       
root.mainloop()

But i got the error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "D:\Anaconda\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "<ipython-input-39-6eb178acbcd6>", line 216, in dataProcessing
    with open(TextFile,encoding="utf8") as IpFile:
TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

May be my approach is not right so, how to resolve this?

askopenfile() actually opens a file for you. You have the following options

Read from the file as is and then close it

file = askopenfile()
for j in file:
    # do your stuff
file.close()

Use the preferred open statement in a similar fashion

with askopenfile() as f:
    # do your stuff

Get the path of the file and open it later. Notice the different function.

file = askopenfilename()
with open(file) as f:
    # do your stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM