How do you delete a file (located in the same directory that your script is running in) in Python?

StackOverflow https://stackoverflow.com/questions/3419457

  •  26-09-2019
  •  | 
  •  

Question

I'm trying to delete a certain file within the directory that I'm running my Python program in.

def erase_custom_file():
    directory=os.listdir(os.getcwd())      
    for somefile in directory:
        if somefile=="file.csv":
           os.remove(???)

I'm not sure what my next step should be. I know that os.remove takes in a path for a parameter but I'm not sure how to direct it to the file I want. Help me please?

Was it helpful?

Solution

Use unlink() and path.join()

>>> try:
...  os.unlink(os.path.join(os.getcwd(),'file.csv'))
... except OSError, e:
...  print e #file does not exist or you don't have permission

OTHER TIPS

This should work:

os.remove( os.path.join( directory, somefile ) )

If you are trying to delete a scratch file you made earlier you can try using temporary files. these will automatically be deleted during garbage collection. reference: http://docs.python.org/library/tempfile.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top