How do you delete a file (located in the same directory that your script is running in) in Python?
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 f开发者_开发问答ile I want. Help me please?
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
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
精彩评论