1

我正在尝试删除运行 Python 程序的目录中的某个文件。

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

我不确定我的下一步应该是什么。我知道这os.remove需要一个参数的路径,但我不确定如何将它定向到我想要的文件。请帮帮我?

4

3 回答 3

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
于 2010-08-05T21:52:30.657 回答
2

这应该有效:

os.remove( os.path.join( directory, somefile ) )
于 2010-08-05T21:50:42.797 回答
0

如果您尝试删除之前创建的临时文件,您可以尝试使用临时文件。这些将在垃圾收集期间自动删除。参考:http ://docs.python.org/library/tempfile.html

于 2010-08-05T22:11:40.523 回答