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

Bri*_*ian 1 python delete-file

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

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

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

Vin*_*vic 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
Run Code Online (Sandbox Code Playgroud)