本文翻译自:Most pythonic way to delete a file which may not exist
I want to delete the file filename
if it exists. 我想删除文件filename
如果存在)。 Is it proper to say 这是否合适
if os.path.exists(filename):
os.remove(filename)
Is there a better way? 有没有更好的办法? A one-line way? 单行方式?
参考:https://stackoom.com/question/jU7J/删除可能不存在的文件的大多数pythonic方式
os.path.exists
returns True
for folders as well as files. os.path.exists
为文件夹和文件返回True
。 Consider using os.path.isfile
to check for whether the file exists instead. 考虑使用os.path.isfile
来检查文件是否存在。
A more pythonic way would be: 一种更加pythonic的方式是:
try:
os.remove(filename)
except OSError:
pass
Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists()
and follows the python convention of overusing exceptions. 虽然这需要更多的行并且看起来非常难看,但它避免了对os.path.exists()
的不必要的调用,并遵循过度使用异常的python约定。
It may be worthwhile to write a function to do this for you: 编写一个函数来为您执行此操作可能是值得的:
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
Something like this? 像这样的东西? Takes advantage of short-circuit evaluation. 利用短路评估。 If the file does not exist, the whole conditional cannot be true, so python will not bother evaluation the second part. 如果文件不存在,则整个条件不能为真,因此python不会打扰第二部分的评估。
os.path.exists("gogogo.php") and os.remove("gogogo.php")
根据Andy Jones的回答,真正的三元操作如何:
os.remove(fn) if os.path.exists(fn) else None
Another way to know if the file (or files) exists, and to remove it, is using the module glob. 另一种知道文件(或文件)是否存在以及将其删除的方法是使用模块glob。
from glob import glob
import os
for filename in glob("*.csv"):
os.remove(filename)
Glob finds all the files that could select the pattern with a *nix wildcard, and loops the list. Glob找到所有可以使用* nix通配符选择模式的文件,并循环列表。