pythonpython-3.xtemporary-filesmkstemp

Specifying file name with mkstemp, file not found


I need to be able to create a temporary file with a specified file name and write data to it, then zip said file with filename up along with other files:

fd, path = tempfile.mkstemp(".bin", "filename", "~/path/to/working/directory/")
try:
    with os.fdopen(fd, "wb") as tmp:
        tmp.write(data)
    with ZipFile("zip.zip", "w") as zip:
        zip.write("filename")        
        zip.writestr("file2", file2_str)
        zip.writestr("file3", file3_str)
        # ...
finally:
    os.remove(path)

I think I must be misunderstanding how mkstemp works, I get the error at the first line of code here:

FileNotFoundError: [Errno 2] No such file or directory: '~/path/to/working/directory/filenameq5st7dey.bin'

It looks like a bunch of garbage gets added to the file name before the suffix is put on the file. I've tried this without a suffix and I still get garbage at the end of the file name.

Aside from the garbage in the file name, why do I get a file not found error instead of having a temporary file created in my directory with that name (plus garbage)?


Solution

  • You supplied this argument:

    "~/path/to/working/directory/"
    

    Perfectly natural, it makes sense why you would supply it. But it is wrong. If you ls . you likely will not find a ~ directory.

    What you were hoping for was expansion to ${HOME}, as the Bourne shell does. In python we must call this function:

    os.path.expanduser("~/path/to/working/directory/")
    

    Print the result it returns and you'll see why it's essential.

    Some folks prefer to have pathlib do the work for them:

    from pathlib import Path
    Path("~/path/to/working/directory/").expanduser()