如何检查是否存在文件,而不使用试用声明?


当前回答

import os
path = /path/to/dir

root,dirs,files = os.walk(path).next()
if myfile in files:
   print "yes it exists"

这在检查多个文件时是有用的,或者你想与现有列表进行一组交叉/分解。

其他回答

它似乎没有一个有意义的功能区别在尝试/排除和isfile(),所以你应该使用哪一个有意义。

如果你想阅读一个文件,如果它存在,

try:
    f = open(filepath)
except IOError:
    print 'Oh dear.'

但是,如果你只是想重新命名一个文件,如果它存在,因此不需要打开它,

if os.path.isfile(filepath):
    os.rename(filepath, filepath + '.old')

如果你想写到文件,如果它不存在,

# Python 2
if not os.path.isfile(filepath):
    f = open(filepath, 'w')

# Python 3: x opens for exclusive creation, failing if the file already exists
try:
    f = open(filepath, 'wx')
except IOError:
    print 'file already exists'

如果你需要文件锁,那是另一个问题。

在2016年,最好的方式仍然是使用os.path.isfile:

>>> os.path.isfile('/path/to/some/file.txt')

在Python 3中,您可以使用Pathlib:

import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
    ...

如何检查是否存在文件,而不使用试用声明?

在2016年,这仍然是最容易的方式来检查是否有文件和是否是文件:

import os
os.path.isfile('./file.txt')    # Returns True if exists, else False

isfile 实际上只是一个内部使用 os.stat 和 stat.S_ISREG(模式) 的辅助方法. 这个 os.stat 是一种低级别的方法,将为您提供有关文件、目录、插件、插件等的详细信息。

注意: 然而,这种方法不会以任何方式锁定文件,因此您的代码可能会受到“检查到使用时间”(TOCTTOU)错误的脆弱性。

因此,提取例外被认为是一个可接受的,和 Pythonic,方法的流量控制在您的程序. 一个人应该考虑处理失去的文件与IOErrors,而不是如果声明(只是一个建议)。

使用 os.path.exist 查看文件和目录:

import os.path
os.path.exists(file_path)

使用 os.path.isfile 仅查看文件(注:以下是符号链接):

os.path.isfile(file_path)

如果你正在检查的原因是,所以你可以做一些类似的文件_存在: open_it(),它更安全地使用一个尝试周围试图打开它。

如果您不打算立即打开文件,您可以使用 os.path.isfile。

如果路径是现有常规文件,则返回是真实的,这跟随了象征性链接,因此 islink() 和 isfile() 都可以对同一条路径是真实的。

import os.path
os.path.isfile(fname) 

如果你需要确保它是一个文件。

从 Python 3.4 开始,Pathlib 模块提供一个以对象为导向的方法(在 Python 2.7 中返回Pathlib2):

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists

要查看一个目录,请:

if my_file.is_dir():
    # directory exists

要检查路径对象是否存在,无论它是否是一个文件或目录,使用存在():

if my_file.exists():
    # path exists

您也可以在尝试区块中使用 resolve(strict=True):

try:
    my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
    # doesn't exist
else:
    # exists