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


当前回答

日期: 2017-12-04

每個可能的解決方案都被列入其他答案中。

一个直观和可争议的方式来检查是否存在文件是如下:

import os

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

# Additionally, check a directory
os.path.isdir('~/folder')  # Returns True if the folder exists, else False

# Check either a directory or a file
os.path.exists('~/file')

我为您的参考做了一个完整的骗局:

# os.path methods in exhaustive cheat sheet
{'definition': ['dirname',
               'basename',
               'abspath',
               'relpath',
               'commonpath',
               'normpath',
               'realpath'],
'operation': ['split', 'splitdrive', 'splitext',
               'join', 'normcase'],
'compare': ['samefile', 'sameopenfile', 'samestat'],
'condition': ['isdir',
              'isfile',
              'exists',
              'lexists'
              'islink',
              'isabs',
              'ismount',],
 'expand': ['expanduser',
            'expandvars'],
 'stat': ['getatime', 'getctime', 'getmtime',
          'getsize']}

其他回答

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

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

要检查是否存在文件,

from sys import argv

from os.path import exists
script, filename = argv
target = open(filename)
print "file exists: %r" % exists(filename)

使用 os.path.exists() 查看是否存在文件:

def fileAtLocation(filename,path):
    return os.path.exists(path + filename)
 

filename="dummy.txt"
path = "/home/ie/SachinSaga/scripts/subscription_unit_reader_file/"


if fileAtLocation(filename,path):
   print('file found at location..')
else:
   print('file not found at location..')

查看文件或目录存在

你可以遵循这三种方式:

使用 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()

不同于 isfile(), exist() 将返回 True for Directory. 因此,根据您是否只需要平板文件或 Directory,您将使用 isfile() 或 exist()。 这里有一些简单的 REPL 输出:

>>> os.path.isfile("/etc/password.txt")
True
>>> os.path.isfile("/etc")
False
>>> os.path.isfile("/does/not/exist")
False
>>> os.path.exists("/etc/password.txt")
True
>>> os.path.exists("/etc")
True
>>> os.path.exists("/does/not/exist")
False