如何在Python中删除同目录下的文件?
我想在运行我的Python程序的文件夹里删除一个特定的文件。
def erase_custom_file():
directory=os.listdir(os.getcwd())
for somefile in directory:
if somefile=="file.csv":
os.remove(???)
我不知道接下来该怎么做。我知道os.remove
需要一个路径作为参数,但我不太清楚怎么指向我想删除的那个文件。请帮帮我好吗?
3 个回答
0
如果你想删除之前创建的临时文件,可以试试使用临时文件。这样的话,这些文件会在垃圾回收的时候自动被删除。
参考链接:http://docs.python.org/library/tempfile.html
2
这个应该可以用:
os.remove( os.path.join( directory, somefile ) )
6
使用 unlink() 和 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