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


当前回答

您可以使用Python的“OS”图书馆:

>>> import os
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt") 
True
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
False

其他回答

不同于 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

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

在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,而不是如果声明(只是一个建议)。

日期: 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']}

使用 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..')

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

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

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

os.path.isfile(file_path)