如何解决TypeError:预期的str, bytes或os.类路径对象,而不是_io.BufferedReader.&



我使用python tkinter创建了一个gui。我遇到了一个问题,我想打开一个文本文件,然后将文件的数据存储到一个列表中。我尝试了以下代码:

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

但是我得到了错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "D:Anacondalibtkinter__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

可能是我的方法不对,所以,如何解决这个问题?

askopenfile()实际上为您打开了一个文件。您有以下选项

按原样从文件中读取,然后关闭它

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

以类似的方式使用首选的open语句

with askopenfile() as f:
# do your stuff

获取文件的路径并稍后打开它。注意不同的函数。

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

最新更新