簡體   English   中英

Python 3 - 打開和保存文件的全部內容

[英]Python 3 - Open and Save files full contents

我正在嘗試使用“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')

有關更多詳細信息和臨時文件文檔,請參閱此答案,因為它默認為期望字節,而不是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM