用python方法检查文件是否存在?(复制)

时间:2022-03-11 22:37:59

This question already has an answer here:

这个问题已经有了答案:

Which is the preferred way to check if a file exists and if not create it?

这是检查文件是否存在的首选方法,是否创建它?

5 个解决方案

#1


241  

To check if a path is an existing file:

检查路径是否为现有文件:

os.path.isfile(path)

os.path.isfile(路径)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

如果路径是现有的常规文件,则返回True。这将遵循符号链接,因此islink()和isfile()都适用于相同的路径。

#2


69  

Instead of os.path.isfile, suggested by others, I suggest using os.path.exists, which checks for anything with that name, not just whether it is a regular file.

而不是os.path。isfile,由其他人建议,我建议使用os.path。存在,它检查任何具有该名称的东西,而不仅仅是它是否是一个普通文件。

Thus:

因此:

if not os.path.exists(filename):
    file(filename, 'w').close()

Alternatively:

另外:

file(filename, 'w+').close()

The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don't have permission to write to it. That's why I prefer the first solution.

如果文件存在,则后者将创建该文件,但不创建其他文件。但是,如果文件存在,它就会失败,但是您没有权限写入它。这就是我喜欢第一种解决方案的原因。

#3


32  

It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.

在我看来,这里所有其他的答案(到目前为止)都没有解决他们提出的解决方案中出现的种族问题。

Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren't looking and causing you problems (or you causing the owner of "that other file" problems).

在您第一次检查文件存在的地方,然后,在您的程序中稍后的几行代码中,您创建它,运行在您没有查找并导致您的问题(或者您导致“其他文件”问题的所有者)的时候创建的文件的风险。

If you want to avoid this sort of thing, I would suggest something like the following (untested):

如果你想避免这类事情,我建议如下(未经测试):

import os

def open_if_not_exists(filename):
    try:
        fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except OSError, e:
        if e.errno == 17:
            print e
            return None
        else:
            raise
    else:
        return os.fdopen(fd, 'w')

This should open your file for writing if it doesn't exist already, and return a file-object. If it does exists, it will print "Ooops" and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).

如果文件不存在,那么应该打开文件,并返回一个文件对象。如果它确实存在,它将打印“Ooops”并返回None(未经测试,仅基于读取python文档,所以可能不是100%正确)。

#4


11  

If (when the file doesn't exist) you want to create it as empty, the simplest approach is

如果(当文件不存在时),您希望将其创建为空,最简单的方法是。

with open(thepath, 'a'): pass

(in Python 2.6 or better; in 2.5, this requires an "import from the future" at the top of your module).

(在Python 2.6或更好的版本中;在2.5中,这需要在模块的顶部“从未来导入”。

If, on the other hand, you want to leave the file alone if it exists, but put specific non-empty contents there otherwise, then more complicated approaches based on if os.path.isfile(thepath):/else statement blocks are probably more suitable.

另一方面,如果您想让文件单独存在,但如果存在特定的非空内容,那么基于os.path.isfile(thepath):/else语句块可能更合适的方法则会更加复杂。

#5


-1  

This was the best way for me. You can retrieve all existing files (be it symbolic links or normal):

这对我来说是最好的方式。您可以检索所有现有的文件(无论是符号链接还是普通文件):

os.path.lexists(path)

os.path.lexists(路径)

Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat().

New in version 2.4.

#1


241  

To check if a path is an existing file:

检查路径是否为现有文件:

os.path.isfile(path)

os.path.isfile(路径)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

如果路径是现有的常规文件,则返回True。这将遵循符号链接,因此islink()和isfile()都适用于相同的路径。

#2


69  

Instead of os.path.isfile, suggested by others, I suggest using os.path.exists, which checks for anything with that name, not just whether it is a regular file.

而不是os.path。isfile,由其他人建议,我建议使用os.path。存在,它检查任何具有该名称的东西,而不仅仅是它是否是一个普通文件。

Thus:

因此:

if not os.path.exists(filename):
    file(filename, 'w').close()

Alternatively:

另外:

file(filename, 'w+').close()

The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don't have permission to write to it. That's why I prefer the first solution.

如果文件存在,则后者将创建该文件,但不创建其他文件。但是,如果文件存在,它就会失败,但是您没有权限写入它。这就是我喜欢第一种解决方案的原因。

#3


32  

It seems to me that all other answers here (so far) fail to address the race-condition that occurs with their proposed solutions.

在我看来,这里所有其他的答案(到目前为止)都没有解决他们提出的解决方案中出现的种族问题。

Any code where you first check for the files existence, and then, a few lines later in your program, you create it, runs the risk of the file being created while you weren't looking and causing you problems (or you causing the owner of "that other file" problems).

在您第一次检查文件存在的地方,然后,在您的程序中稍后的几行代码中,您创建它,运行在您没有查找并导致您的问题(或者您导致“其他文件”问题的所有者)的时候创建的文件的风险。

If you want to avoid this sort of thing, I would suggest something like the following (untested):

如果你想避免这类事情,我建议如下(未经测试):

import os

def open_if_not_exists(filename):
    try:
        fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    except OSError, e:
        if e.errno == 17:
            print e
            return None
        else:
            raise
    else:
        return os.fdopen(fd, 'w')

This should open your file for writing if it doesn't exist already, and return a file-object. If it does exists, it will print "Ooops" and return None (untested, and based solely on reading the python documentation, so might not be 100% correct).

如果文件不存在,那么应该打开文件,并返回一个文件对象。如果它确实存在,它将打印“Ooops”并返回None(未经测试,仅基于读取python文档,所以可能不是100%正确)。

#4


11  

If (when the file doesn't exist) you want to create it as empty, the simplest approach is

如果(当文件不存在时),您希望将其创建为空,最简单的方法是。

with open(thepath, 'a'): pass

(in Python 2.6 or better; in 2.5, this requires an "import from the future" at the top of your module).

(在Python 2.6或更好的版本中;在2.5中,这需要在模块的顶部“从未来导入”。

If, on the other hand, you want to leave the file alone if it exists, but put specific non-empty contents there otherwise, then more complicated approaches based on if os.path.isfile(thepath):/else statement blocks are probably more suitable.

另一方面,如果您想让文件单独存在,但如果存在特定的非空内容,那么基于os.path.isfile(thepath):/else语句块可能更合适的方法则会更加复杂。

#5


-1  

This was the best way for me. You can retrieve all existing files (be it symbolic links or normal):

这对我来说是最好的方式。您可以检索所有现有的文件(无论是符号链接还是普通文件):

os.path.lexists(path)

os.path.lexists(路径)

Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat().

New in version 2.4.