Search code examples
pythonfileinvalid-argumentoserror

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


Trying to create backup for my files:

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)

Error I'm getting:

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

Is the problem in duplicating files?


Solution

  • You're overwritting file with result of open. So use different variable names, and use with so the file descriptor is closed automatically

    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)