9

I am using tempfile.NamedTemporaryFile() to store some text until the program ends. On Unix is working without any issues but on Windows the file returned isn't accessible for reading or writing: python gives Errno 13. The only way is to set delete=False and manually delete the file with os.remove(). Why?

Rnhmjoj
  • 863
  • 1
  • 10
  • 18
  • Can you show us the code where you use it? Needing `delete=False` as a workaround implies it is deleted because you closed the file. – Martijn Pieters Mar 23 '13 at 15:10
  • Ok, I've found the problem. Sometimes the file needs to be erased, to do that I use `open(tempfile.name,"w").close()`. This causes the IOError because the file can be opened only once after it is created. Now, how can I erase its contents without open it again? – Rnhmjoj Mar 23 '13 at 17:14
  • I think you wanted to *truncate* the file; call `.seek(0)` then `.truncate()`. – Martijn Pieters Mar 23 '13 at 17:44
  • @Rnhmjoj The `close()` does the magic! Saved my day! – Ron Jan 13 '22 at 07:58

3 Answers3

5

This causes the IOError because the file can be opened only once after it is created.

The reason is because NamedTemporaryFile creates the file with FILE_SHARE_DELETE flag on Windows. On Windows when a file has been created/opened with specific share flag all subsequent open operations have to pass this share flag. It's not the case with Python's open function which does not pass FILE_SHARE_DELETE flag. See my answer on How to create a temporary file that can be read by a subprocess? question for more details and a workaround.

Community
  • 1
  • 1
Piotr Dobrogost
  • 41,292
  • 40
  • 236
  • 366
1

Take a look: http://docs.python.org/2/library/tempfile.html

 tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])

This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the file object. 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). If delete is true (the default), the file is deleted as soon as it is closed.

Leo Chapiro
  • 13,678
  • 8
  • 61
  • 92
0

Thanks to @Rnhmjoj here is a working solution:

    file = NamedTemporaryFile(delete=False)
    file.close()

You have to keep the file with the delete-flag and then close it after creation. This way, Windows will unlock the file and you can do stuff with it!

Ron
  • 22,128
  • 31
  • 108
  • 206