Python Forum

Full Version: remove file from current project
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I created a file and after done it is opened and saved by user. I then need to delete from my current directory in my project. I tried the remove method but not working!

file = str(pdf_file_name) # file name is similar to something.pdf
location= "C:/abc/efg/"
path = os.path.join(location, file)
os.remove(path)
I get this error:
Error:
'something.pdf' is not recognized as an internal or external command, operable program or batch file.
test if the file exists

this works

from os import path, remove

def file_remover(file):
    if path.exists(file):
        remove(file)
        print('file removed')
    else:
        print('file does not exist')

file_remover('test.pdf')
Output:
file removed
Please note:
Add after line 3 (only until working) print(f"path: {path}")
try results from command line to make sure it's formed correctly:
Linux: ls -l path
MS Windows: use dir command

Also note, From docs:
Quote: On Windows, attempting to remove a file that is in use causes an exception to be raised; on Unix, the directory entry is removed but the storage allocated to the file is not made available until the original file is no longer in use.
Make sure file is closed before removing.