python - Python 文件保存错误无效

标签 python python-3.x tkinter savefiledialog

我正在尝试编写一个脚本,允许用户使用他们想要的任何名称创建文件夹,然后使用他们想要的任何名称创建文件。一旦他们这样做了,程序就会要求他们提供 3 个名字并将它们写入文件中。然后我想让用户输入 1 到 3 之间的数字并显示他们想要的行数。我现在在尝试读取文件时遇到错误,其中包含以下内容:

TypeError: invalid file: <_io.TextIOWrapper name='C:blah blah ' mode='a' encoding='cp1252'>

代码如下:

def SaveDir():
    global FileSave
    FileSave = filedialog.asksaveasfile(mode='a', defaultextension=".txt")
    if FileSave is None:                                                                                                                                          
        return
    print(FileSave)
    SaveDir2()

def SaveDir2():
    FinalFile = open(FileSave)
    FinalFile.write(PRINTCONV)
    FinalFile.close()

最佳答案

函数tkFileDialog.asksaveasfile返回实际打开的文件,这就是为什么您收到 TypeEror 的原因,因为这不是可以打开的有效文件名。考虑使用 tkFileDialog.asksaveasfilename 来代替。或者,只需调用FileSave.write,因为打开的文件对象。

以前曾问过类似的问题:

关于python - Python 文件保存错误无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31257674/

相关文章:

python - py2exe 给出运行时错误 : Too early to create image

python - 在 Pycharm 中对类装饰属性进行类型检查

python - 通过变量获取属性

python - 导入错误 : Could not import settings 'health_tweets.settings' No module named health_tweets. 设置

python - 如何将协程添加到正在运行的 asyncio 循环中?

python - 在 python 中使用 Tkinter 用图像制作干净的背景

python - 如何减少 if/elif 语句中的重复代码

python - 在 Python 中使用事件监控系统

python-3.x - 在列表理解: invalid syntax中引发异常

python - 在运行时单击时如何更改按钮的颜色?