我正在尝试使用“askopenfilename”打开一个文件,然后将该文件的内容保存到一个新文件中。然后我可以打开那个新文件进行修改。但是,当我尝试这样做时,我遇到了错误。任何帮助表示赞赏。
def startapp(self):
self.grid()
filebutton = tkinter.Button(self, text="Open File for Selection button", command=self.getfile)
filebutton.grid(column=1, row=0)
quitbutton = tkinter.Button(self, text="Quit", command=quit)
quitbutton.grid(column=2, row=0)
self.grid_columnconfigure(0, weight=1)
def getfile(self): #this is the open file function
selectedfile = filedialog.askopenfilename(filetypes=[('All files', '*.*')])
temp = tempfile.TemporaryFile()
temp.write(selectedfile)
提供的错误:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "C:/Users/**/PycharmProjects/FileAnalyser/FileAnalyser1/GUI/ParentWindow.py", line 31, in getfile
temp.write(selectedfile)
File "C:\Python34\lib\tempfile.py", line 399, in func_wrapper
return func(*args, **kwargs)
TypeError: 'str' does not support the buffer interface
最佳答案
看起来您正在尝试将文本(字符串)写入此文件。如果是这样,您需要在通过更改创建 TemporaryFile
时指定非二进制模式
temp = tempfile.TemporaryFile()
到
temp = tempfile.TemporaryFile(mode='w')
请参阅 this answer 了解更多详细信息,并查看 tempfile docs 以了解它默认为字节而不是字符串这一事实。
关于Python 3 - 打开和保存文件的全部内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31678950/