如何,如果它存在,删除文件?

问题描述 投票:5回答:4

我怎么能是否存在一个目录与Python 2.7使用os / app删除一个文件?

我试着

os.remove('directory/file.png')

但如果该项目不存在的,我得到了一个错误。

python python-2.7
4个回答
8
投票
try:
    os.remove(path)
except OSError:
    pass

刚刚捕获错误并忽略它。 (忽略错误是不是你对所有错误做,但在这里,它就是你想要的。)


3
投票
if os.path.exists(path):
    os.remove(path)

0
投票

检查是否存在先:

if os.path.exists(path):
    os.remove(path)

0
投票

使用异常:

try:
    os.remove("file_name")
except:
    return "something went wrong"
© www.soinside.com 2019 - 2024. All rights reserved.