开发者

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

开发者 https://www.devze.com 2023-01-10 16:12 出处:网络
I\'m trying to delete a certain file within the directory that I\'m running my Python program in. def erase_custom_file():

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号