gpt4 book ai didi

python - 删除可能不存在的文件的大多数pythonic方法

转载 作者:IT老高 更新时间:2023-10-28 12:03:53 25 4
gpt4 key购买 nike

如果文件 filename 存在,我想删除它。说得对吗

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

有没有更好的方法?单线方式?

最佳答案

更pythonic的方式是:

try:
os.remove(filename)
except OSError:
pass

虽然这需要更多的行并且看起来很丑陋,但它避免了对 os.path.exists() 的不必要调用,并遵循了过度使用异常的 python 约定。

编写一个函数来为您执行此操作可能是值得的:

import os, errno

def silentremove(filename):
try:
os.remove(filename)
except OSError as e: # this would be "except OSError, e:" before Python 2.6
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occurred

关于python - 删除可能不存在的文件的大多数pythonic方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10840533/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com