删除文件的大多数pythonic方法

问题:删除文件的大多数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

os.path.exists返回True文件夹和文件。考虑使用os.path.isfile来检查文件是否存在。

os.path.exists 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=Truepathlib.Path.unlinkdocs此处

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的答案是较老的Python和Kevin的正确答案的正确答案,答案是较新的的正确答案。

如果您不想复制的功能silentremove,则此功能在path.py中显示remove_p

from path import Path
Path(filename).remove_p()

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-rmsudo 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]