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


当前回答

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

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

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

os.path.isfile(file_path)

其他回答

os.path - posixpath.py (ntpath.py) genericpath.py - 行 ~20+ def exists(path): ""“测试是否有一条路径存在. Returns False for broken symbolic links”"" try: st = os.stat(path) except os.error: return False return True

或:

3、文件系统跨功能

因为这些在文件夹上,(在大多数情况下)它们对我们的问题是无效的(有例外,如非野卡的全球化 - 如 @ShadowRanger指出),所以我不会坚持它们。

os.access("/tmp", os.F_OK)

Linux(Ubuntu(维基百科:Ubuntu版史) 16 x86_64 (pc064)) 也相当于:

笔记:

但是,因为这更像一个工人,我在这里停下来。

6、SysAdmin方法

我认为这是一个(Lame)工作室(gainarie):使用Python作为一个插槽来执行盾牌命令:

底线:

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

if os.path.isfile(filepath):
   print("File exists")
import os
os.path.exists(path) # Returns whether the path (directory or file) exists or not
os.path.isfile(path) # Returns whether the file exists or not

您可以使用 os.listdir 检查文件是否在特定目录中。

import os
if 'file.ext' in os.listdir('dirpath'):
    #code