Skip to main content
 首页 » 编程设计

python之如何在 Python 中删除文件(位于脚本运行的同一目录中)

2025年05月04日14傻小

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

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

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

请您参考如下方法:

使用 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