Python 3 - 打开和保存文件的全部内容

标签 python python-3.x openfiledialog temporary-files savefiledialog

我正在尝试使用“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/

相关文章:

c# - 如何将表单添加到控制台应用程序以便用户可以选择文件?

python - 查找字符串中的行数

c# - 打开文件对话框。 "Specify Directory Dialog"怎么样?

python - SciPy 与 MKL 库的兼容性问题

python - 为什么输出只包含 2 个值而不包含整个图像的位移?

python-3.x - 如何使用 python 从 XML 创建嵌套字典?

python-3.x - Python 中的隔离森林

c# - 检测浏览器中是否弹出打开文件对话框

python - Google Colab - 无法打开任何笔记本

python - 用数组索引多维数组