Ishmal Ijaz
Ishmal Ijaz

Reputation: 5727

Temporary file not deletable?

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'

Upvotes: 3

Views: 1553

Answers (2)

Muhammad Usman
Muhammad Usman

Reputation: 1258

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

Upvotes: 2

Muhammad Usman
Muhammad Usman

Reputation: 1258

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)

Upvotes: 4

Related Questions