“OSError: [Errno 22] Invalid argument” - 重复文件?

"OSError: [Errno 22] Invalid argument" - duplicate files?

提问人:BrinyFlyer28795 提问时间:5/27/2023 最后编辑:BrinyFlyer28795 更新时间:5/27/2023 访问量:62

问:

尝试为我的文件创建备份:

name = input("Enter the name:" (\"/\" to quit)\n>>>")
name += ".vcblr"
write_file(name, ([], [], [], []))

def write_file(file, content) -> None:

    file = open(f"PythonVocabulary/{file}", "wb")
    pickle.dump(content, file)

    file = open(f"PythonVocabulary/backup/{file}", "wb")
    pickle.dump(content, file)

我收到错误:

OSError: [Errno 22] Invalid argument: "PythonVocabulary/backup/<_io.BufferedWriter name='PythonVocabulary/german.vcblr'>"

复制文件有问题吗?

python 文件 无效参数 oserror

评论

2赞 azro 5/27/2023
你没看到吗? 不是字符串,也不是文件名,而是 BufferedWriter 对象。请编辑并共享调用该方法的代码和给定文件的定义<_io.BufferedWriter name='PythonVocabulary/german.vcblr'>filevariable
0赞 wjandrea 5/27/2023
@azro 仔细检查后,该参数被返回值 覆盖。因此,看起来可以通过重命名参数并在 f 字符串中使用它来解决此问题。fileopenfilename
0赞 wjandrea 5/27/2023
欢迎来到 Stack Overflow!请参加导览并阅读 如何询问 有关提示,例如制作一个最小的可重复示例,这有助于发现这样的错别字。
0赞 wjandrea 5/27/2023
需要明确的是,Windows 上的文件名中不允许使用。<>
0赞 wjandrea 5/27/2023
旁注:打开文件的最佳做法是使用 like .官方教程中对此进行了介绍。我会为第二个文件使用不同的名称,比如说。withwith open(fname) as f: pickle.dump(...)with open(...) as file_backup

答:

1赞 azro 5/27/2023 #1

你对 .因此,请使用不同的变量名称,并使用 so 文件描述符会自动关闭fileopenwith

def write_file(filename, content) -> None:
    with open(f"PythonVocabulary/{filename}", "wb") as file:
        pickle.dump(content, file)

    with open(f"PythonVocabulary/backup/{filename}", "wb") as file:
        pickle.dump(content, file)