不使用try语句如何查看文件是否存在?


#1楼

首选try语句。 它被认为是更好的风格,并且避免了比赛条件。

不要相信我。 这个理论有很多支持。 这是一对:

  • 样式: http ://allendowney.com/sd/notes/notes11.txt的“处理异常情况”部分
  • 避免比赛条件

#2楼

这是检查文件是否存在的最简单方法。 仅仅因为文件在您检查时存在并不保证在您需要打开文件时该文件就会存在。

import os
fname = "foo.txt"
if os.path.isfile(fname):print("file does exist at this time")
else:print("no such file exists at this time")

#3楼

在try / except和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'

如果您需要文件锁定,那是另一回事。


#4楼

Python 3.4+具有一个面向对象的路径模块: pathlib 。 使用这个新模块,您可以检查文件是否存在,如下所示:

import pathlib
p = pathlib.Path('path/to/file')
if p.is_file():  # or p.is_dir() to see if it is a directory# do stuff

您可以(通常应该)在打开文件时仍然使用try/except块:

try:with p.open() as f:# do awesome stuff
except OSError:print('Well darn.')

pathlib模块中包含许多很酷的东西:方便的globing,检查文件的所有者,更容易的路径连接等。值得一试。 如果您使用的是旧版Python(2.6版或更高版本),则仍可以使用pip安装pathlib:

# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2

然后按如下所示导入它:

# Older Python versions
import pathlib2 as pathlib

#5楼

您无需try:即可撰写Brian的建议try:

from contextlib import suppresswith suppress(IOError), open('filename'):process()

suppress是Python 3.4的一部分。 在较早的发行版中,您可以快速编写自己的隐匿:

from contextlib import contextmanager@contextmanager
def suppress(*exceptions):try:yieldexcept exceptions:pass

#6楼

如果该文件用于打开,则可以使用以下技术之一:

>>> with open('somefile', 'xt') as f: #Using the x-flag, Python3.3 and above
...     f.write('Hello\n')>>> if not os.path.exists('somefile'):
...     with open('somefile', 'wt') as f:
...         f.write("Hello\n")
... else:
...     print('File already exists!')

更新

为了避免混淆,并根据我得到的答案,当前答案会找到具有给定名称的文件目录。


#7楼

您可以使用Python的“ OS”库:

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

#8楼

虽然我总是建议使用tryexcept语句,但是这里有几种可能(我个人最喜欢使用os.access ):

  1. 尝试打开文件:

    打开文件将始终验证文件是否存在。 您可以像下面这样创建一个函数:

     def File_Existence(filepath): f = open(filepath) return True 

    如果为False,它将在更高版本的Python中以未处理的IOError或OSError停止执行。 要捕获异常,您必须使用tryexcept子句。 当然,您总是可以像这样使用try try`语句(感谢hsandt让我思考):

     def File_Existence(filepath): try: f = open(filepath) except IOError, OSError: # Note OSError is for later versions of Python return False return True 
  2. 使用os.path.exists(path)

    这将检查您指定的内容是否存在。 但是,它会检查文件目录,因此请注意如何使用它们。

     import os.path >>> os.path.exists("this/is/a/directory") True >>> os.path.exists("this/is/a/file.txt") True >>> os.path.exists("not/a/directory") False 
  3. 使用os.access(path, mode)

    这将检查您是否有权访问该文件。 它将检查权限。 根据os.py文档,输入os.F_OK ,它将检查路径的存在。 但是,使用此方法会创建一个安全漏洞,因为有人可以使用检查权限到打开文件之间的时间来攻击您的文件。 您应该直接打开文件,而不要检查其权限。 ( EAFP与LBYP )。 如果您以后不打算打开文件,而仅检查其存在,则可以使用它。

    无论如何,在这里:

     >>> import os >>> os.access("/is/a/file.txt", os.F_OK) True 

我还应该提到,有两种方法将使您无法验证文件的存在。 要么是问题被permission denied要么是no such file or directory 。 如果捕获到IOError ,请将IOError设置IOError as e (就像我的第一个选项一样),然后键入print(e.args)以便希望确定问题。 希望对您有所帮助! :)


#9楼

if os.path.isfile(path_to_file):try: open(path_to_file)passexcept IOError as e:print "Unable to open file"

引发异常被认为是程序中流控制的可接受且Pythonic的方法。 考虑使用IOErrors处理丢失的文件。 在这种情况下,如果文件存在但用户没有读取权限,则将引发IOError异常。

SRC: http : //www.pfinn.net/python-check-if-file-exists.html


#10楼

import os
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):   print "File found!"
else:print "File not found!"

导入os可以更轻松地在操作系统中导航和执行标准操作。

供参考,请参阅如何使用Python检查文件是否存在?

如果需要高级操作,请使用shutil


#11楼

import os.pathdef isReadableFile(file_path, file_name):full_path = file_path + "/" + file_nametry:if not os.path.exists(file_path):print "File path is invalid."return Falseelif not os.path.isfile(full_path):print "File does not exist."return Falseelif not os.access(full_path, os.R_OK):print "File cannot be read."return Falseelse:print "File can be read."return Trueexcept IOError as ex:print "I/O error({0}): {1}".format(ex.errno, ex.strerror)except Error as ex:print "Error({0}): {1}".format(ex.errno, ex.strerror)return False
#------------------------------------------------------path = "/usr/khaled/documents/puzzles"
fileName = "puzzle_1.txt"isReadableFile(path, fileName)

#12楼

如何在不使用try语句的情况下使用Python检查文件是否存在?

从Python 3.4开始可用,导入并实例化具有文件名的Path对象,并检查is_file方法(请注意,对于指向常规文件的符号链接,该方法也返回True):

>>> from pathlib import Path
>>> Path('/').is_file()
False
>>> Path('/initrd.img').is_file()
True
>>> Path('/doesnotexist').is_file()
False

如果您使用的是Python 2,则可以从pypi, pathlib2移植pathlib模块,或者从os.path模块检查isfile

>>> import os
>>> os.path.isfile('/')
False
>>> os.path.isfile('/initrd.img')
True
>>> os.path.isfile('/doesnotexist')
False

现在,上面可能是这里最好的实用直接答案,但是有可能出现竞争情况(取决于您要完成的工作),并且底层实现使用try ,但Python在其所有地方都使用try的事实实施。

由于Python在任何地方都使用try ,因此实际上没有理由避免使用它的实现。

但是此答案的其余部分试图考虑这些警告。

更长,更古怪的答案

从Python 3.4开始可用,请在pathlib使用新的Path对象。 请注意, .exists并不完全正确,因为目录不是文件(从Unix的意义上讲, 一切都是文件)。

>>> from pathlib import Path
>>> root = Path('/')
>>> root.exists()
True

因此,我们需要使用is_file

>>> root.is_file()
False

这是is_file的帮助:

is_file(self)Whether this path is a regular file (also True for symlinks pointingto regular files).

因此,让我们获得一个我们知道是文件的文件:

>>> import tempfile
>>> file = tempfile.NamedTemporaryFile()
>>> filepathobj = Path(file.name)
>>> filepathobj.is_file()
True
>>> filepathobj.exists()
True

默认情况下, NamedTemporaryFile在关闭时删除文件(并且当不再有引用时会自动关闭)。

>>> del file
>>> filepathobj.exists()
False
>>> filepathobj.is_file()
False

但是,如果深入研究实现 ,您会发现is_file使用try

def is_file(self):"""Whether this path is a regular file (also True for symlinks pointingto regular files)."""try:return S_ISREG(self.stat().st_mode)except OSError as e:if e.errno not in (ENOENT, ENOTDIR):raise# Path doesn't exist or is a broken symlink# (see https://bitbucket.org/pitrou/pathlib/issue/12/)return False

比赛条件:为什么我们喜欢尝试

我们喜欢try因为它避免了比赛条件。 使用try ,您只需尝试读取文件,期望它在那里,否则,您将捕获异常并执行有意义的后备行为。

如果要在尝试读取文件之前检查文件是否存在,并且可能要删除它,然后使用多个线程或进程,或者另一个程序知道该文件并可能将其删除,则可能会遇到以下风险:如果您检查竞赛条件是否存在,则为竞赛条件 ,因为您随后在其条件 (存在)变化之前就竞相打开它。

竞争条件很难调试,因为存在一个很小的窗口,在竞争窗口中它们可能导致您的程序失败。

但是,如果这是您的动力,则可以通过使用suppress上下文管理器获得try语句的价值。

在没有try语句的情况下避免竞争条件: suppress

Python 3.4为我们提供了suppress上下文管理器(以前为ignore上下文管理器),它在更少的行中在语义上完全相同,而(至少表面上)满足了避免try语句的原始要求:

from contextlib import suppress
from pathlib import Path

用法:

>>> with suppress(OSError), Path('doesnotexist').open() as f:
...     for line in f:
...         print(line)
...
>>>
>>> with suppress(OSError):
...     Path('doesnotexist').unlink()
...
>>>

对于较早的Python,您可以使用自己的suppress ,但是如果不try则比使用它们更冗长。 我确实相信这实际上是唯一可以在Python 3.4之前的版本中不使用try答案,因为它使用了上下文管理器代替:

class suppress(object):def __init__(self, *exceptions):self.exceptions = exceptionsdef __enter__(self):return selfdef __exit__(self, exc_type, exc_value, traceback):if exc_type is not None:return issubclass(exc_type, self.exceptions)

尝试一下可能会更容易:

from contextlib import contextmanager@contextmanager
def suppress(*exceptions):try:yieldexcept exceptions:pass

不符合要求的其他选项“不尝试”:

文件

import os
os.path.isfile(path)

从文档 :

os.path.isfile(path)

如果path是现有的常规文件,则返回True。 这遵循符号链接,因此,对于同一路径, islink()isfile()都可以为true。

但是,如果您检查此函数的来源 ,您会发现它确实使用了try语句:

 # This follows symbolic links, so both islink() and isdir() can be true # for the same path on systems that support symlinks def isfile(path): """Test whether a path is a regular file""" try: st = os.stat(path) except os.error: return False return stat.S_ISREG(st.st_mode) 
>>> OSError is os.error
True

它所要做的就是使用给定的路径查看它是否可以获取统计信息,捕获OSError ,然后检查它是否是文件(如果没有引发异常)。

如果您打算对文件进行某些操作,建议您使用try-except直接尝试它,以避免出现竞争情况:

try:with open(path) as f:f.read()
except OSError:pass

os.access

os.access可用于Unix和Windows,但要使用它必须传递标志,并且它不能区分文件和目录。 这更用于测试真正的调用用户是否在提升的特权环境中具有访问权限:

import os
os.access(path, os.F_OK)

它还遭受与isfile相同的竞争条件问题。 从文档 :

注意:在实际使用open()之前,使用access()检查用户是否被授权打开文件,这会造成安全漏洞,因为用户可能会利用检查和打开文件之间的较短时间间隔来对其进行操作。 最好使用EAFP技术。 例如:

 if os.access("myfile", os.R_OK): with open("myfile") as fp: return fp.read() return "some default data" 

最好写成:

 try: fp = open("myfile") except IOError as e: if e.errno == errno.EACCES: return "some default data" # Not a permission error. raise else: with fp: return fp.read() 

避免使用os.access 。 与上面讨论的高级对象和功能相比,它是一种低级功能,具有更多的用户错误机会。

批评另一个答案:

另一个答案是关于os.access

就我个人而言,我更喜欢这个,因为它在后台调用了本机API(通过“ $ {PYTHON_SRC_DIR} /Modules/posixmodule.c”),但是它也为可能的用户错误打开了大门,并且它不像其他变体那样具有Python风格:

这个答案说它偏爱非Pythonic且容易出错的方法,没有理由。 似乎鼓励用户使用不了解它们的低级API。

它还创建了一个上下文管理器,通过无条件返回True ,允许所有异常(包括KeyboardInterruptSystemExit !)以静默方式传递,这是隐藏错误的好方法。

这似乎鼓励用户采用不良做法。


#13楼

这是用于Linux命令行环境的1行Python命令。 我觉得这个非常好,因为我不是一个很酷的Bash家伙。

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

我希望这是有帮助的。


#14楼

在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():...

#15楼

我是一个已经存在大约十年的软件包的作者,它的功能可以直接解决这个问题。 基本上,如果您使用的是非Windows系统,它将使用Popen访问find 。 但是,如果您使用的是Windows,它将使用高效的文件系统walker复制find

该代码本身不使用try块……除非确定操作系统,然后将您引导至“ Unix”风格的find或手动编译find 。 时序测试表明, try确定操作系统的速度更快,因此我确实在那里使用了操作系统(但没有其他地方)。

>>> import pox
>>> pox.find('*python*', type='file', root=pox.homedir(), recurse=False)
['/Users/mmckerns/.python']

还有文件

>>> print pox.find.__doc__
find(patterns[,root,recurse,type]); Get path to a file or directorypatterns: name or partial name string of items to search forroot: path string of top-level directory to searchrecurse: if True, recurse down from root directorytype: item filter; one of {None, file, dir, link, socket, block, char}verbose: if True, be a little verbose about the searchOn some OS, recursion can be specified by recursion depth (an integer).patterns can be specified with basic pattern matching. Additionally,multiple patterns can be specified by splitting patterns with a ';'For example:>>> find('pox*', root='..')['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']>>> find('*shutils*;*init*')['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']>>>

如果您愿意看的话,可以在这里找到实现: https : //github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190


#16楼

再添加一个细微的变化,而其他变化未完全反映出来。

这将处理file_pathNone或为空字符串的情况。

def file_exists(file_path):if not file_path:return Falseelif not os.path.isfile(file_path):return Falseelse:return True

根据Shahbaz的建议添加变体

def file_exists(file_path):if not file_path:return Falseelse:return os.path.isfile(file_path)

根据Peter Wood的建议添加变体

def file_exists(file_path):return file_path and os.path.isfile(file_path):

#17楼

使用os.path.isfile()os.path.isdir()os.path.exists()测试文件和文件夹

假定“路径”是有效路径,此表显示了每个函数对文件和文件夹返回的内容:

您还可以使用os.path.splitext()来获取扩展名(如果您尚不知道os.path.splitext()以测试文件是否为某种文件类型

>>> import os
>>> path = "path to a word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True

#18楼

如何在不使用try语句的情况下检查文件是否存在?

在2016年,可以说这仍然是检查文件是否同时存在以及是否是文件的最简单方法:

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

isfile实际上只是一个内部使用os.statstat.S_ISREG(mode)的帮助程序方法。 此os.stat是一个较低层的方法,它将为您提供有关文件,目录,套接字,缓冲区等的详细信息。 有关os.stat的更多信息

注意:但是,这种方法不会以任何方式锁定文件,因此您的代码可能容易受到“ 检查时间到使用时间 ”( TOCTTOU )错误的攻击

因此,引发异常被认为是程序中流控制的可接受且Pythonic的方法。 并且应该考虑使用IOErrors处理丢失的文件,而不是if语句( 只是建议 )。


#19楼

尽管在(至少一个)现有答案中已经列出了几乎所有可能的方法(例如,添加了Python 3.4特定的内容),但我将尝试将所有内容组合在一起。

注意 :我要发布的每个Python标准库代码都属于3.5.3版。

问题陈述

  1. 检查文件( 可以争论 :也是文件夹(“特殊”文件)吗?)是否存在
  2. 不要使用try / except / else / finally

可能的解决方案

  1. [Python 3]:os.path。 存在path ) (也请检查其他函数族成员,例如os.path.isfileos.path.isdiros.path.lexists的行为是否稍有不同)

     os.path.exists(path) 

    如果path引用现有路径或打开的文件描述符,则返回True 。 对于断开的符号链接返回False 。 在某些平台上,即使未实际执行路径 ,如果未授予在请求的文件上执行os.stat()的权限,此函数也可能返回False

    一切都很好,但是如果遵循导入树:

    • os.path - posixpath.py(ntpath.py)

      • genericpath.py ,第〜#20 +行

         def exists(path): """Test whether a path exists. Returns False for broken symbolic links""" try: st = os.stat(path) except os.error: return False return True 

    它只是[Python 3]周围的try / 除了块:操作系统。 statpath,*,dir_fd = None,follow_symlinks = True ) 。 因此,您的代码是try / 除外(免费),但在帧堆栈中至少有一个这样的块。 这也适用于其他功能( 包括 os.path.isfile )。

    1.1。 [Python 3]:路径。 is_file ()

    • 这是一种处理路径的更好的方式(以及更多的python ic), 但是
    • 后台 ,它做的完全一样( pathlib.py ,行〜#1330 ):

       def is_file(self): """ Whether this path is a regular file (also True for symlinks pointing to regular files). """ try: return S_ISREG(self.stat().st_mode) except OSError as e: if e.errno not in (ENOENT, ENOTDIR): raise # Path doesn't exist or is a broken symlink # (see https://bitbucket.org/pitrou/pathlib/issue/12/) return False 
  2. [Python 3]:使用语句上下文管理器 。 要么:

    • 创建一个:

       class Swallow: # Dummy example swallowed_exceptions = (FileNotFoundError,) def __enter__(self): print("Entering...") def __exit__(self, exc_type, exc_value, exc_traceback): print("Exiting:", exc_type, exc_value, exc_traceback) return exc_type in Swallow.swallowed_exceptions # only swallow FileNotFoundError (not eg TypeError - if the user passes a wrong argument like None or float or ...) 
      • 而它的用法-我会复制os.path.isfile行为(请注意,这只是为了演示目的, 不要试图写生产这样的代码):

         import os import stat def isfile_seaman(path): # Dummy func result = False with Swallow(): result = stat.S_ISREG(os.stat(path).st_mode) return result 
    • 使用[Python 3]:contextlib。 抑制 (*例外 ) -它是专门用于选择性地抑制异常设计

    但是,它们似乎是try / except / else / finally块的包装,如[Python 3]: with语句指出:

    除了 最终使用模式外,这可以允许常见的尝试封装,以方便重用。

  3. 文件系统遍历功能(并在结果中搜索匹配项)

    • [Python 3]:操作系统。 listdirpath ='。' ) (或在Python v 3.5 +上的[Python 3]:操作系统scandirpath ='。' ) ,向后移植: [PyPI]:scandir )

      • 在引擎盖下,两者都使用:

        • Nix : [man7]:OPENDIR(3) / [man7]:READDIR(3) / [man7]:CLOSEDIR(3)
        • Win : [MS.Docs]:FindFirstFileW函数 / [MS.Docs]:FindNextFileW函数 / [MS.Docs]:FindClose函数

        通过[GitHub]:python / cpython-(master)cpython / Modules / posixmodule.c

      使用scandir()而不是listdir()可以显着提高还需要文件类型或文件属性信息的代码的性能,因为如果操作系统在扫描目录时提供了os.DirEntry对象,则该信息会公开。 所有的os.DirEntry方法都可以执行系统调用,但是is_dir()和is_file()通常只需要系统调用即可进行符号链接。 os.DirEntry.stat()在Unix上始终需要系统调用,而在Windows上只需要一个系统调用即可。

    • [Python 3]:操作系统。 步行top,topdown = True,onerror = None,followlinks = False
      • 它使用os.listdiros.scandir时为os.scandir
    • [Python 3]:glob。 iglobpathname,*,recursive = False ) (或其前身: glob.glob
      • 本身似乎没有遍历功能(至少在某些情况下),但仍使用os.listdir

    由于这些遍历文件夹,(在大多数情况下)它们对于我们的问题效率不高(有一些例外,例如非通配glob bing-如@ShadowRanger所指出的),所以我不再坚持使用它们。 更不用说在某些情况下,可能需要处理文件名。

  4. [Python 3]:操作系统。 行为接近os.path.exists 访问path,mode,*,dir_fd = None,Effective_ids = False,follow_symlinks = True ) (实际上它更宽,主要是由于第二个参数)

    • 用户权限可能会限制文件“可见性”,如doc所述:

      ...测试调用用户是否具有对path的指定访问权限。 模式应该为F_OK以测试路径的存在...

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

    由于我也使用C语言 ,因此我也使用此方法,因为在后台它调用了本机API (同样,通过“ $ {PYTHON_SRC_DIR} /Modules/posixmodule.c” )),但是它也为可能的用户打开了一扇门errors ,它不像其他变体那样像Python ic。 因此,正如@AaronHall正确指出的那样,除非您知道自己在做什么,否则不要使用它:

    • Nix : [man7]:ACCESS(2) (!!!请注意有关其用法可能引入的安全漏洞的注意事项!!!)
    • : [MS.Docs]:GetFileAttributesW函数

    注意 :也可以通过[Python 3]调用本地APIctypes -Python的外部函数库 ,但是在大多数情况下,它更为复杂。

    (特定于Win ):由于vcruntime *msvcr * ). dll导出[MS.Docs]:_access,_waccess函数族,因此以下示例:

     Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os, ctypes >>> ctypes.CDLL("msvcrt")._waccess(u"C:\\\\Windows\\\\System32\\\\cmd.exe", os.F_OK) 0 >>> ctypes.CDLL("msvcrt")._waccess(u"C:\\\\Windows\\\\System32\\\\cmd.exe.notexist", os.F_OK) -1 

    注意事项

    • 尽管这不是一个好习惯,但我在调用中使用了os.F_OK ,但这只是为了清楚起见(其值为0
    • 我正在使用_waccess,以便相同的代码可在Python3Python2上使用 (尽管它们之间存在与Unicode相关的区别)
    • 尽管这是针对非常特定的领域, 但之前的任何答案都未提及

    LnxUbtu(16 x64) )对应项也是如此:

     Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os, ctypes >>> ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6").access(b"/tmp", os.F_OK) 0 >>> ctypes.CDLL("/lib/x86_64-linux-gnu/libc.so.6").access(b"/tmp.notexist", os.F_OK) -1 

    注意事项

    • 而是硬编码libc的路径( “ /lib/x86_64-linux-gnu/libc.so.6” ),该路径在整个系统之间可能(而且很可能会有所不同), (或空字符串)可以传递给CDLL构造函数( ctypes.CDLL(None).access(b"/tmp", os.F_OK) )。 根据[man7]:DLOPEN(3) :

      如果filename为NULL,则返回的句柄用于主程序。 当赋予dlsym ()时,此句柄将在主程序中搜索符号,然后在程序启动时加载所有共享对象,然后在dlopen ()中加载带有标志RTLD_GLOBAL的所有共享对象。

      • 主(当前)程序( python )与libc链接,因此将加载其符号(包括access
      • 必须小心处理,因为像mainPy_Main和(所有)其他函数都可用。 打电话给他们可能会造成灾难性的影响(对当前程序)
      • 这也不适用于Win (但是这没什么大不了的,因为msvcrt.dll位于“%SystemRoot%\\ System32”中 ,默认情况下位于%PATH%中 )。 我想更进一步,在Win上复制此行为(并提交补丁),但事实证明, [MS.Docs]:GetProcAddress函数仅“看到” 导出的符号,因此除非有人在主可执行文件中声明该函数作为__declspec(dllexport) (为什么地球上的普通的人会做的?),主程序加载,但几乎无法使用
  5. 安装一些具有文件系统功能的第三方模块

    最有可能的,将依赖于上述方法之一(可能需要进行一些自定义)。
    一个示例是(再次,特定于Win ) [GitHub]:mhammond / pywin32-Windows专用的Python(pywin32)Extensions ,它是WINAPIPython包装器。

    但是,由于这更像是一种解决方法,所以我在这里停止。

  6. 另一个( lam )解决方法( gainarie )是(我喜欢这样称呼) sysadmin方法:使用Python作为包装器执行Shell命令

    • 获胜

       (py35x64_test) e:\\Work\\Dev\\StackOverflow\\q000082831>"e:\\Work\\Dev\\VEnvs\\py35x64_test\\Scripts\\python.exe" -c "import os; print(os.system('dir /b \\"C:\\\\Windows\\\\System32\\\\cmd.exe\\" > nul 2>&1'))" 0 (py35x64_test) e:\\Work\\Dev\\StackOverflow\\q000082831>"e:\\Work\\Dev\\VEnvs\\py35x64_test\\Scripts\\python.exe" -c "import os; print(os.system('dir /b \\"C:\\\\Windows\\\\System32\\\\cmd.exe.notexist\\" > nul 2>&1'))" 1 
    • 尼克斯LnxUbtu )):

       [cfati@cfati-ubtu16x64-0:~]> python3 -c "import os; print(os.system('ls \\"/tmp\\" > /dev/null 2>&1'))" 0 [cfati@cfati-ubtu16x64-0:~]> python3 -c "import os; print(os.system('ls \\"/tmp.notexist\\" > /dev/null 2>&1'))" 512 

底线

  • 使用try / except / else / finally块,因为它们可以防止您遇到一系列令人讨厌的问题。 我可以想到的一个反例是性能:此类块非常昂贵,因此请不要将它们放在应该每秒运行数十万次的代码中(但由于(在大多数情况下,由于)它涉及磁盘访问,事实并非如此)。

最后说明

  • 我将尝试使其保持最新状态,欢迎提出任何建议,我将结合所有有用的内容,使之成为答案

#20楼

如果您已经导入NumPy用于其他目的,则无需导入其他库,例如pathlibospaths等。

import numpy as np
np.DataSource().exists("path/to/your/file")

这将根据其存在返回true或false。


#21楼

日期:2017-12-04

每个可能的解决方案都已在其他答案中列出。

一种检查文件是否存在的直观且可争论的方法如下:

import os
os.path.isfile('~/file.md')  # Returns True if exists, else False
# additionaly check a dir
os.path.isdir('~/folder')  # Returns True if the folder exists, else False
# check either a dir or a file
os.path.exists('~/file')

我做了详尽的备忘单供您参考:

#os.path methods in exhaustive cheatsheet
{'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']}

#22楼

您可以尝试这样做(更安全):

try:# http://effbot.org/zone/python-with-statement.htm# 'with' is safer to open a filewith open('whatever.txt') as fh:# Do something with 'fh'
except IOError as e:print("({})".format(e))

输出为:

([Errno 2]没有这样的文件或目录:'whatever.txt')

然后,根据结果,您的程序可以仅从那里继续运行,也可以编写代码以停止它。


#23楼

检查文件或目录是否存在

您可以遵循以下三种方式:

注意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+中,可通过pip安装在Python 2中)

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

#24楼

import os.pathif os.path.isfile(filepath):

#25楼

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

#26楼

您具有os.path.exists函数:

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

这对于文件和目录都返回True ,但是您可以改用

os.path.isfile(file_path)

测试它是否是专门的文件。 它遵循符号链接。


#27楼

如果您要检查的原因是可以执行诸如if file_exists: open_it() ,则try尝试打开它更安全。 检查然后打开可能会导致文件被删除或移动,或者介于检查和尝试打开文件之间。

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

如果path是现有的常规文件,则返回True 。 这遵循符号链接,因此,对于同一路径, islink()和isfile()都可以为true。

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

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

从Python 3.4开始, pathlib模块提供了一种面向对象的方法(在Python 2.7中pathlib2移植到pathlib2 ):

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

要检查目录,请执行以下操作:

if my_file.is_dir():# directory exists

要检查Path对象是否独立于文件或目录而exists() ,请使用exists()

if my_file.exists():# path exists

您还可以在try块中使用resolve(strict=True)

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

#28楼

另外, os.access()

if os.access("myfile", os.R_OK):with open("myfile") as fp:return fp.read()

作为R_OKW_OKX_OK的标志来测试权限( doc )。


#29楼

不像isfile() exists()将返回True的目录。
因此,取决于您只需要纯文件还是目录,您将使用isfile()isfile() exists() 。 这是一个简单的REPL输出。

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

#30楼

结合使用os.path.isfile()os.access()

import os
import os.pathPATH='./file.txt'if os.path.isfile(PATH) and os.access(PATH, os.R_OK):print "File exists and is readable"
else:print "Either the file is missing or not readable"

如何检查文件是否存在无例外?相关推荐

  1. io.h源码 检查文件是否存在

    请问在windows上使用什么API来检查文件是否存在? http://topic.csdn.net/u/20080929/00/48833cf7-125f-4075-881f-614a51fc3e6 ...

  2. 如何检查文件是否是python中的目录或常规文件? [重复]

    本文翻译自:how to check if a file is a directory or regular file in python? [duplicate] Possible Duplicat ...

  3. android 判断文件是否存在_每日一课 | Python检查文件是否存在

    在Python中,我们可以使用os.path.isfile()或pathlib.Path.is_file()(Python 3.4)来检查文件是否存在.1. pathlibPython 3.4的新功能 ...

  4. c语言读取acc文件的采样率,C语言文件操作:打开检查文件指针访问模式

    如何检查已打开的文件指针的访问模式? 所以说一个函数传递一个已经打开的文件指针: //Pseudo code bool PseudoFunction(FILE *Ptr) { if(... Inser ...

  5. python 检查文件是否存在_Python中如何判断文件是否存在?

    这里介绍三种判断文件或文件夹是否存在的方法,分别使用os模块.Try语句.pathlib模块. 1.使用os模块 os模块中的os.path.exists()方法用于检验文件是否存在. import ...

  6. halcon file_exists 检查文件是否存在

    目录 file_exists(算子) 描述 参数 file_exists(算子) file_exists - 检查文件是否存在. file_exists(:: FileName:FileExists) ...

  7. test命令用法。功能:检查文件和比较值

    test命令用法.功能:检查文件和比较值 1)判断表达式 if test  (表达式为真) if test !表达式为假 test 表达式1 –a 表达式2                  两个表达 ...

  8. vb6如何判断文件是否存在_使用boost.filesystem检查文件是否存在的正确姿势

    在我参与的项目中,使用了boost.filesystem进行文件操作.boost.filesystem在发生错误的时候会抛出异常,但是在大部分情况下这些异常是可以忽略的,例如,在检查文件是否存在的时候 ...

  9. java 检测目录下的文件_如何在Java中检查文件是目录还是文件

    java 检测目录下的文件 java.io.File class contains two methods using which we can find out if the file is a d ...

最新文章

  1. python中frameset中的元素怎么识别_python3.6+selenium实现操作Frame中的页面元素
  2. OpenCASCADE:使用 XSTEPDRAW
  3. 二维数组子数组矩形和
  4. 我国企业对开源社区的贡献度_开源社区对我意味着什么
  5. java printf与println_浅析Java中print、printf、println的区别
  6. 分享一个VS2013代码窗口一闪而过的解决方案。
  7. Go语言与数据库开发:01-02
  8. git常用命令及手动关联git本地和远端仓库
  9. Mujoco编程开发-官方文档
  10. 焕然一新的 Vue 3 中文文档来了
  11. 后直播时代的技术弄潮儿——TRTC
  12. SaaS模式和传统软件模式有什么区别?
  13. 【NOIP2016】魔法阵(节选自冬雪_狂舞_桀骜-xmy的博客)
  14. idear怎么设置自动导包
  15. ios修改apn的插件_iPhone手机APN修改方案
  16. esxi安装威联通_威联通TS-453Bmini NAS加装内存,轻松玩转虚拟机安装win10系统
  17. H3C 胖AP设置(非VLAN模式)
  18. Oracle入门精读14_Lsnrctl命令
  19. 5G 与 MEC 边缘计算
  20. JS字符串过滤数字_过滤大写数字

热门文章

  1. 算法-------三角形最小路径和(Java版本)
  2. 第四周项目五-用递归方法求解(求n的阶乘)
  3. 使用Android Studio新建Project并建立多个module
  4. ubuntu16.04安装retext,第一行图标flie,edit,help没有,其它图标也不显示?
  5. UITableViewHeader 动态调整高度
  6. UIView的AddChildViewCtroller的用法(4中页面切换方式)
  7. iOS进阶之架构设计MVVM的理解(3)
  8. ##管家婆项目(service层)
  9. Install FileZilla in Ubuntu16.04
  10. 【iOS】Xcode 使用 CocoaPods 导入第三方库后没有提示