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


当前回答

它似乎没有一个有意义的功能区别在尝试/排除和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'

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

其他回答

使用:

import os

# For testing purposes the arguments defaulted to the current folder and file.
# returns True if file found
def file_exists(FOLDER_PATH='../', FILE_NAME=__file__):
    return os.path.isdir(FOLDER_PATH) \
        and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))

它基本上是一个文件夹检查,然后使用 os.path.join 使用适当的目录分离器进行文件检查。

这里是一个单线的Python命令为Linux命令线环境,我觉得这是非常有用的,因为我不是那么热的Bash男孩。

python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"

虽然我总是建议使用尝试和除陈述,这里有几个选项为您(我的个人喜爱是使用os.access):

尝试打开文件:打开文件将始终确认文件的存在. 你可以这样做一个函数: def File_Existence(filepath): f = open(filepath) return True 如果它是错误的,它将停止执行与未经处理的 IOError 或 OSError 在后续版本的 Python. 要捕获例外,你必须使用一个尝试,除了条款。

我还应该提到,有两种方式,你将无法验证一个文件的存在. 无论问题将被拒绝许可或没有这样的文件或目录. 如果你抓住一个IOError,设置IOError为e(如我的第一个选项),然后输入打印(e.args),以便你可以希望确定你的问题. 我希望它有助于! :)

如果你正在检查的原因是,所以你可以做一些类似的文件_存在: 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

查看文件或目录存在

你可以遵循这三种方式:

使用 isfile( )

注意1: os.path.isfile 仅用于文件

import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists

二、使用存在

注意2: os.path.exists 用于文件和目录

import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) # True if directory exists

pathlib.Path 方法(包含在 Python 3+ 中,可与 Python 2 的 pip 安装)

from pathlib import Path
Path(filename).exists()