tags:

views:

62

answers:

3

Hi, 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? Thanks!

+1  A: 

This should work:

os.remove( os.path.join( directory, somefile ) )
robert
+1 for os.path.join - one of the things often poorly reinvented
delnan
+5  A: 

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
Vinko Vrsalovic
Thank you! This worked best with my code!
Brian
A: 

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

Andy