3

I have create the temporary file using the tempfile.mkstemp() and after creating this, I have get the unique path of the file inside the path and now I want to delete the temporary file. My code is given below.

I have already visit this WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'new.dat' but did not solve my problem.

Code

import os
import tempfile

path=tempfile.mkstemp('.png', 'bingo',
    'C:\\Users\\MuhammadUsman\\Documents\\PythonScripts\\Project')
os.unlink(path)

Error

PermissionError: [WinError 32] The process cannot access the file
because it is being used by another process:
'C:\\Users\\MuhammadUsman\\Documents\\PythonScripts\\Project\\bingois3q1b3u.png'
martineau
  • 119,623
  • 25
  • 170
  • 301
Ishmal Ijaz
  • 5,317
  • 3
  • 11
  • 17
  • tell me the reason of why down voted. Read the question carefully. I have tried many possible combinations .Don't down voted without reading the questions. – Ishmal Ijaz May 25 '18 at 00:41
  • 1
    Temporary files usually delete themselves automatically if created via the `tempfile` module, so you probably don't need to be trying to do it manually. – martineau May 25 '18 at 00:55
  • Hmm, is it possible that your problem is that you're trying to access a file in the user directory for "MuhammadUsman"? Did you perhaps copy and paste that from another post on SO without updating the path with your user name? – Tim Johns May 25 '18 at 01:00
  • > Temporary files usually delete themselves automatically... [I'm afraid not.](https://superuser.com/a/318514/451162) – Matt Hancock Jul 26 '20 at 14:51

2 Answers2

4

Try this: this works for me.

import os
import tempfile

fd,path=tempfile.mkstemp('.png', 'bingo', 'C:\\Users\\MuhammadUsman\\Documents\\Python Scripts\\Project')
os.close(fd)
os.unlink(path)
Muhammad Usman
  • 1,220
  • 13
  • 22
  • 1
    Explanation: Python's use of the pseudo-POSIX `_open` function happens cause issues due to Windows being a bit inconsistent on use of `FILE_SHARE_DELETE` mode. [Some related info on CPython bug tracker](https://bugs.python.org/issue14243). Basically, the sharing mode used by `mkstemp` and `unlink` disagrees, so the file can't be opened for delete until the handle from `mkstemp` is closed. – ShadowRanger May 25 '18 at 01:18
2

If you only want to get the unique name then try this. This is better than the upper solution. There is no need to delete the file. File automatically will be deleted.

import os
import tempfile

path=tempfile.NamedTemporaryFile(dir='C:\\Users\\MuhammadUsman\\Documents\\Python Scripts\\Project',suffix='.png').name
Muhammad Usman
  • 1,220
  • 13
  • 22