问题:删除文件的大多数pythonic方法
我要删除该文件(filename
如果存在)。说的合适吗
if os.path.exists(filename):
os.remove(filename)
有没有更好的办法?单行方式?
I want to delete the file filename
if it exists. Is it proper to say
if os.path.exists(filename):
os.remove(filename)
Is there a better way? A one-line way?
回答 0
一种更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
A more pythonic way would be:
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.
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
回答 1
我更喜欢抑制异常,而不是检查文件的存在,以避免TOCTTOU错误。Matt的答案就是一个很好的例子,但是我们可以在Python 3下使用contextlib.suppress()
以下方法稍微简化一下:
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
如果filename
是一个pathlib.Path
对象而不是字符串,我们可以调用其.unlink()
方法而不是使用os.remove()
。以我的经验,Path对象比字符串更有用。
由于此答案中的所有内容都是Python 3专有的,因此它提供了另一个升级理由。
I prefer to suppress an exception rather than checking for the file’s existence, to avoid a TOCTTOU bug. Matt’s answer is a good example of this, but we can simplify it slightly under Python 3, using contextlib.suppress()
:
import contextlib
with contextlib.suppress(FileNotFoundError):
os.remove(filename)
If filename
is a pathlib.Path
object instead of a string, we can call its .unlink()
method instead of using os.remove()
. In my experience, Path objects are more useful than strings for filesystem manipulation.
Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade.
回答 2
returns True
for folders as well as files. Consider using os.path.isfile
to check for whether the file exists instead.
回答 3
本着安迪·琼斯(Andy Jones)的回答精神,如何进行真正的三元运算:
os.remove(fn) if os.path.exists(fn) else None
In the spirit of Andy Jones’ answer, how about an authentic ternary operation:
os.remove(fn) if os.path.exists(fn) else None
回答 4
知道文件是否存在并删除的另一种方法是使用模块glob。
from glob import glob
import os
for filename in glob("*.csv"):
os.remove(filename)
Glob查找所有可以使用* nix通配符选择模式的文件,并循环列表。
Another way to know if the file (or files) exists, and to remove it, is using the module 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.
回答 5
从Python 3.8开始,请使用missing_ok=True
和pathlib.Path.unlink
(docs此处)
from pathlib import Path
my_file = Path("./dir1/dir2/file.txt")
# Python 3.8+
my_file.unlink(missing_ok=True)
# Python 3.7 and earlier
if my_file.exists():
my_file.unlink()
As of Python 3.8, use missing_ok=True
and pathlib.Path.unlink
(docs here)
from pathlib import Path
my_file = Path("./dir1/dir2/file.txt")
# Python 3.8+
my_file.unlink(missing_ok=True)
# Python 3.7 and earlier
if my_file.exists():
my_file.unlink()
回答 6
Matt’s answer is the right one for older Pythons and Kevin’s the right answer for newer ones.
If you wish not to copy the function for silentremove
, this functionality is exposed in path.py as remove_p:
from path import Path
Path(filename).remove_p()
回答 7
if os.path.exists(filename): os.remove(filename)
是单线的。
你们中的许多人可能会不同意(可能是出于考虑将三元体系建议使用为“丑陋”的理由)的想法,但这引出了一个问题,即当人们习惯将丑陋标准称为“非丑陋”时,我们是否应该听取他们的意见。
if os.path.exists(filename): os.remove(filename)
is a one-liner.
Many of you may disagree – possibly for reasons like considering the proposed use of ternaries “ugly” – but this begs the question of whether we should listen to people used to ugly standards when they call something non-standard “ugly”.
回答 8
在Python 3.4或更高版本中,pythonic方式为:
import os
from contextlib import suppress
with suppress(OSError):
os.remove(filename)
In Python 3.4 or later version, the pythonic way would be:
import os
from contextlib import suppress
with suppress(OSError):
os.remove(filename)
回答 9
像这样吗 利用短路评估。如果文件不存在,则整个条件不能为真,因此python不会麻烦评估第二部分。
os.path.exists("gogogo.php") and os.remove("gogogo.php")
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.
os.path.exists("gogogo.php") and os.remove("gogogo.php")
回答 10
亲吻提供:
def remove_if_exists(filename):
if os.path.exists(filename):
os.remove(filename)
然后:
remove_if_exists("my.file")
A KISS offering:
def remove_if_exists(filename):
if os.path.exists(filename):
os.remove(filename)
And then:
remove_if_exists("my.file")
回答 11
这是另一个解决方案:
if os.path.isfile(os.path.join(path, filename)):
os.remove(os.path.join(path, filename))
This is another solution:
if os.path.isfile(os.path.join(path, filename)):
os.remove(os.path.join(path, filename))
回答 12
带有您自己的消息的另一种解决方案。
import os
try:
os.remove(filename)
except:
print("Not able to delete the file %s" % filename)
Another solution with your own message in exception.
import os
try:
os.remove(filename)
except:
print("Not able to delete the file %s" % filename)
回答 13
我曾经用过rm
,它可以强制删除不存在的文件,并可以将其--preserve-root
作为选项rm
。
--preserve-root
do not remove `/' (default)
rm --help | grep "force"
-f, --force ignore nonexistent files and arguments, never prompt
我们也可以使用safe-rm(sudo apt-get install safe-rm
)
Safe-rm是一种安全工具,旨在通过使用包装程序替换/ bin / rm来防止重要文件的意外删除,该包装程序将对给定的参数与永不删除的可配置文件和目录黑名单进行检查。
首先,我检查文件夹/文件路径是否存在。这将防止设置变量fileToRemove /
folderToRemove to the string
-r /`。
import os, subprocess
fileToRemove = '/home/user/fileName';
if os.path.isfile(fileToRemove):
subprocess.run(['rm', '-f', '--preserve-root', fileToRemove]
subprocess.run(['safe-rm', '-f', fileToRemove]
I have used rm
which can force to delete nonexistent files with --preserve-root
as an option to rm
.
--preserve-root
do not remove `/' (default)
rm --help | grep "force"
-f, --force ignore nonexistent files and arguments, never prompt
We can also use safe-rm (sudo apt-get install safe-rm
)
Safe-rm is a safety tool intended to prevent the accidental deletion of important files by replacing /bin/rm with a wrapper, which checks the given arguments against a configurable blacklist of files and directories that should never be removed.
First I check whether folder/file path exist or not. This will prevent setting variable fileToRemove/
folderToRemoveto the string
-r /`.
import os, subprocess
fileToRemove = '/home/user/fileName';
if os.path.isfile(fileToRemove):
subprocess.run(['rm', '-f', '--preserve-root', fileToRemove]
subprocess.run(['safe-rm', '-f', fileToRemove]
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。