How do I persist to disk a temporary file using Python?

前端 未结 4 2028
难免孤独
难免孤独 2021-02-02 09:35

I am attempting to use the \'tempfile\' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as usi

4条回答
  •  走了就别回头了
    2021-02-02 10:07

    hop is right, and dF. is incorrect on why the error occurs.

    Since you haven't called f.close() yet, the file is not removed.

    The doc for NamedTemporaryFile says:

    Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

    And for TemporaryFile:

    Under Unix, the directory entry for the file is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

    Therefore, to persist a temporary file (on Windows), you can do the following:

    import tempfile, shutil
    f = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
    f.write('foo')
    file_name = f.name
    f.close()
    shutil.copy(file_name, 'bar.txt')
    os.remove(file_name)
    

    The solution Hans Sjunnesson provided is also off, because copyfileobj only copies from file-like object to file-like object, not file name:

    shutil.copyfileobj(fsrc, fdst[, length])

    Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption. Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.

提交回复
热议问题