简体   繁体   English

如何检查文件是否存在无异常?

[英]How do I check whether a file exists without exceptions?

How do I check whether a file exists or not, without using the try statement?如何在不使用try语句的情况下检查文件是否存在?

If the reason you're checking is so you can do something like if file_exists: open_it() , it's safer to use a try around the attempt to open it.如果您检查的原因是您可以执行类似if file_exists: open_it()的操作,那么在尝试打开它时使用try会更安全。 Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.检查然后打开可能会导致文件被删除或移动,或者在检查和尝试打开文件之间存在风险。

If you're not planning to open the file immediately, you can use os.path.isfile如果您不打算立即打开文件,可以使用os.path.isfile

Return True if path is an existing regular file.如果 path 是现有的常规文件,则返回True This follows symbolic links, so both islink() and isfile() can be true for the same path.这遵循符号链接,因此islink()isfile()对于同一路径都可以为真。

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

if you need to be sure it's a file.如果您需要确定它是一个文件。

Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):从 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

To check a directory, do:要检查目录,请执行以下操作:

if my_file.is_dir():
    # directory exists

To check whether a Path object exists independently of whether is it a file or directory, use exists() :要检查Path对象是否独立于它是文件还是目录而存在,请使用exists()

if my_file.exists():
    # path exists

You can also use resolve(strict=True) in a try block:您还可以在try块中使用resolve(strict=True)

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

Use os.path.exists to check both files and directories:使用os.path.exists检查文件和目录:

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

Use os.path.isfile to check only files (note: follows symlinks):使用os.path.isfile仅检查文件(注意:遵循符号链接):

os.path.isfile(file_path)

Unlike isfile() , exists() will return True for directories.isfile()不同, exists()将为目录返回True So depending on if you want only plain files or also directories, you'll use isfile() or exists() .因此,根据您是否只需要普通文件或目录,您将使用isfile()exists() Here is some simple REPL output:这是一些简单的 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
import os

if os.path.isfile(filepath):
   print("File exists")

Use os.path.isfile() with os.access() :os.path.isfile()os.access()一起使用:

import os

PATH = './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")
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

Although almost every possible way has been listed in (at least one of) the existing answers (eg Python 3.4 specific stuff was added), I'll try to group everything together.尽管几乎所有可能的方式都列在(至少一个)现有答案中(例如添加了Python 3.4特定的东西),但我会尝试将所有内容组合在一起。

Note : every piece of Python standard library code that I'm going to post, belongs to version 3.5.3 .注意:我要发布的每一段Python标准库代码都属于3.5.3版本。

Problem statement :问题陈述

  1. Check file ( arguable : also folder ("special" file) ?) existence检查文件(有争议:还有文件夹(“特殊”文件)?)存在
  2. Don't use try / except / else / finally blocks不要使用try / except / else / finally

Possible solutions :可能的解决方案

  1. [Python 3]: os.path. [Python 3]:os.path。 exists ( path ) (also check other function family members like os.path.isfile , os.path.isdir , os.path.lexists for slightly different behaviors) 存在( path ) (还检查其他函数系列成员,如os.path.isfileos.path.isdiros.path.lexists的行为略有不同)

     os.path.exists(path)

    Return True if path refers to an existing path or an open file descriptor.如果path引用现有路径或打开的文件描述符,则返回True Returns False for broken symbolic links.对于损坏的符号链接返回False On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.在某些平台上,如果未授予对请求的文件执行os.stat()的权限,即使路径物理存在,此函数也可能返回False

    All good, but if following the import tree:一切都好,但如果遵循导入树:

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

      • genericpath.py , line ~#20+ 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

    it's just a try / except block around [Python 3]: os.这只是 [Python 3] 周围的try / except:os. stat ( path, *, dir_fd=None, follow_symlinks=True ) . stat路径,*,dir_fd=None,follow_symlinks=True So, your code is try / except free, but lower in the framestack there's (at least) one such block.因此,您的代码是try / except free,但在框架堆栈的较低位置(至少)有一个这样的块。 This also applies to other funcs ( including os.path.isfile ).这也适用于其他功能(包括os.path.isfile )。

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

    • It's a fancier (and more python ic) way of handling paths, but这是一种处理路径的更高级(和更多python ic)的方式,但是
    • Under the hood, it does exactly the same thing ( pathlib.py , line ~#1330 ):在引擎盖下,它做的事情完全相同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]: With Statement Context Managers . [Python 3]:使用语句上下文管理器 Either:任何一个:

    • Create one:创建一个:

       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 ...)
      • And its usage - I'll replicate the os.path.isfile behavior (note that this is just for demonstrating purposes, do not attempt to write such code for production ):及其用法 - 我将复制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
    • Use [Python 3]: contextlib.使用[Python 3]:contextlib。 suppress ( *exceptions ) - which was specifically designed for selectively suppressing exceptions 抑制( *exceptions ) -为选择性抑制异常而设计


    But, they seem to be wrappers over try / except / else / finally blocks, as [Python 3]: The with statement states:但是,它们似乎是try / except / else / finally块的包装器,如[Python 3]: with语句指出:

    This allows common try ... except ...finally usage patterns to be encapsulated for convenient reuse.这允许封装常见的try ... except ...finally使用模式以方便重用。

  3. Filesystem traversal functions (and search the results for matching item(s))文件系统遍历函数(并搜索匹配项的结果)


    Since these iterate over folders, (in most of the cases) they are inefficient for our problem (there are exceptions, like non wildcarded glob bing - as @ShadowRanger pointed out), so I'm not going to insist on them.由于这些迭代文件夹,(在大多数情况下)它们对我们的问题效率低下(有例外,如非通配符glob bing - 正如@ShadowRanger 指出的那样),所以我不会坚持使用它们。 Not to mention that in some cases, filename processing might be required.更不用说在某些情况下,可能需要文件名处理。

  4. [Python 3]: os. [Python 3]:操作系统。 access ( path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True ) whose behavior is close to os.path.exists (actually it's wider, mainly because of the 2 nd argument) access ( path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True )其行为接近os.path.exists (实际上它更宽,主要是因为第二个参数)

    • user permissions might restrict the file "visibility" as the doc states:正如文档所述,用户权限可能会限制文件“可见性”:

      ...test if the invoking user has the specified access to path . ...测试调用用户是否具有对path的指定访问权限。 mode should be F_OK to test the existence of path...模式应该是F_OK来测试路径的存在...

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

    Since I also work in C , I use this method as well because under the hood, it calls native API s (again, via "${PYTHON_SRC_DIR}/Modules/posixmodule.c" ), but it also opens a gate for possible user errors , and it's not as Python ic as other variants.由于我也在C中工作,因此我也使用此方法,因为在后台,它调用本机API (再次通过"${PYTHON_SRC_DIR}/Modules/posixmodule.c" ),但它也为可能的用户打开了一扇门errors ,它不像其他变体那样是Python ic。 So, as @AaronHall rightly pointed out, don't use it unless you know what you're doing:因此,正如@AaronHall 正确指出的那样,除非您知道自己在做什么,否则不要使用它:

    Note : calling native API s is also possible via [Python 3]: ctypes - A foreign function library for Python , but in most cases it's more complicated.注意:也可以通过 [Python 3] 调用本机API ctypes - Python 的外部函数库,但在大多数情况下它更复杂。

    ( Win specific): Since vcruntime* ( msvcr* ) .dll exports a [MS.Docs]: _access, _waccess function family as well, here's an example: (特定于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

    Notes :备注

    • Although it's not a good practice, I'm using os.F_OK in the call, but that's just for clarity (its value is 0 )虽然这不是一个好习惯,但我在调用中使用os.F_OK ,但这只是为了清楚起见(其值为0
    • I'm using _waccess so that the same code works on Python3 and Python2 (in spite of unicode related differences between them)我正在使用_waccess以便在Python3Python2上运行相同的代码(尽管它们之间存在unicode相关的差异)
    • Although this targets a very specific area, it was not mentioned in any of the previous answers虽然这针对一个非常具体的领域,但在之前的任何答案中都没有提到


    The Lnx ( Ubtu (16 x64) ) counterpart as well: Lnx ( Ubtu (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

    Notes :备注

    • Instead hardcoding libc 's path ( "/lib/x86_64-linux-gnu/libc.so.6" ) which may (and most likely, will) vary across systems, None (or the empty string) can be passed to CDLL constructor ( ctypes.CDLL(None).access(b"/tmp", os.F_OK) ).相反,硬编码libc的路径( “/lib/x86_64-linux-gnu/libc.so.6” )可能(并且很可能会)因系统而异,(或空字符串)可以传递给CDLL构造函数( ctypes.CDLL(None).access(b"/tmp", os.F_OK) )。 According to [man7]: DLOPEN(3) :根据[man7]: DLOPEN(3)

      If filename is NULL, then the returned handle is for the main program.如果filename为 NULL,则返回的句柄用于主程序。 When given to dlsym (), this handle causes a search for a symbol in the main program, followed by all shared objects loaded at program startup, and then all shared objects loaded by dlopen () with the flag RTLD_GLOBAL .当给dlsym () 时,这个句柄会导致在主程序中搜索一个符号,然后是在程序启动时加载的所有共享对象,然后是由dlopen () 加载的所有共享对象,带有标志RTLD_GLOBAL

      • Main (current) program ( python ) is linked against libc , so its symbols (including access ) will be loaded主(当前)程序( python )与libc链接,因此将加载其符号(包括access
      • This has to be handled with care, since functions like main , Py_Main and (all the) others are available;这必须小心处理,因为mainPy_Main和(所有)其他函数都是可用的; calling them could have disastrous effects (on the current program)调用它们可能会产生灾难性影响(在当前程序上)
      • This doesn't also apply to Win (but that's not such a big deal, since msvcrt.dll is located in "%SystemRoot%\System32" which is in %PATH% by default).这也不适用于Win (但这没什么大不了的,因为msvcrt.dll位于“%SystemRoot%\System32”中,默认情况下位于%PATH%中)。 I wanted to take things further and replicate this behavior on Win (and submit a patch), but as it turns out, [MS.Docs]: GetProcAddress function only "sees" exported symbols, so unless someone declares the functions in the main executable as __declspec(dllexport) (why on Earth the regular person would do that?), the main program is loadable but pretty much unusable我想更进一步并在Win上复制此行为(并提交补丁),但事实证明, [MS.Docs]:GetProcAddress 函数仅“看到”导出的符号,因此除非有人在主可执行文件中声明这些函数作为__declspec(dllexport) (为什么普通人会这样做?),主程序是可加载的,但几乎无法使用
  5. Install some third-party module with filesystem capabilities安装一些具有文件系统功能的第三方模块

    Most likely, will rely on one of the ways above (maybe with slight customizations).最有可能的是,将依赖上述方式之一(可能有轻微的定制)。
    One example would be (again, Win specific) [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions , which is a Python wrapper over WINAPI s.一个例子是(同样,特定于Win[GitHub]:mhammond/pywin32 - Python for Windows (pywin32) Extensions ,它是WINAPI上的Python包装器。

    But, since this is more like a workaround, I'm stopping here.但是,由于这更像是一种解决方法,所以我在这里停下来。

  6. Another (lame) workaround ( gainarie ) is (as I like to call it,) the sysadmin approach: use Python as a wrapper to execute shell commands另一个(蹩脚的)解决方法( gainarie )是(我喜欢这样称呼它)系统管理员方法:使用Python作为包装器来执行 shell 命令

    • Win :

       (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
    • Nix ( Lnx ( Ubtu )):尼克斯Lnx乌图)):

       [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

Bottom line :底线

  • Do use try / except / else / finally blocks, because they can prevent you running into a series of nasty problems.一定使用try / except / else / finally块,因为它们可以防止你遇到一系列讨厌的问题。 A counter-example that I can think of, is performance: such blocks are costly, so try not to place them in code that it's supposed to run hundreds of thousands times per second (but since (in most cases) it involves disk access, it won't be the case).我能想到的一个反例是性能:这样的块很昂贵,所以尽量不要将它们放在应该每秒运行数十万次的代码中(但因为(在大多数情况下)它涉及磁盘访问,不会是这样)。

Final note(s) :最后说明

  • I will try to keep it up to date, any suggestions are welcome, I will incorporate anything useful that will come up into the answer我会尽量保持最新,欢迎任何建议,我会将任何有用的东西纳入答案

Python 3.4+ has an object-oriented path module: pathlib . Python 3.4+有一个面向对象的路径模块: pathlib Using this new module, you can check whether a file exists like this:使用这个新模块,您可以像这样检查文件是否存在:

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

You can (and usually should) still use a try/except block when opening files:您可以(并且通常应该)在打开文件时仍然使用try/except块:

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

The pathlib module has lots of cool stuff in it: convenient globbing, checking file's owner, easier path joining, etc. It's worth checking out. pathlib 模块中有很多很酷的东西:方便的通配符、检查文件的所有者、更简单的路径连接等。值得一试。 If you're on an older Python (version 2.6 or later), you can still install pathlib with pip:如果您使用的是较旧的 Python(2.6 版或更高版本),您仍然可以使用 pip 安装 pathlib:

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

Then import it as follows:然后按如下方式导入:

# Older Python versions
import pathlib2 as pathlib

This is the simplest way to check if a file exists.这是检查文件是否存在的最简单方法。 Just because the file existed when you checked doesn't guarantee that it will be there when you need to open it.仅仅因为您检查时该文件存在并不能保证在您需要打开它时它会在那里。

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")

How do I check whether a file exists, using Python, without using a try statement?如何在不使用 try 语句的情况下使用 Python 检查文件是否存在?

Now available since Python 3.4, import and instantiate a Path object with the file name, and check the is_file method (note that this returns True for symlinks pointing to regular files as well):现在从 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

If you're on Python 2, you can backport the pathlib module from pypi, pathlib2 , or otherwise check isfile from the os.path module:如果您使用的是 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

Now the above is probably the best pragmatic direct answer here, but there's the possibility of a race condition (depending on what you're trying to accomplish), and the fact that the underlying implementation uses a try , but Python uses try everywhere in its implementation.现在上面可能是这里最好的实用直接答案,但是存在竞争条件的可能性(取决于您要完成的任务),以及底层实现使用try的事实,但 Python 在它的任何地方都使用try执行。

Because Python uses try everywhere, there's really no reason to avoid an implementation that uses it.因为 Python 在任何地方都使用try ,所以没有理由避免使用它的实现。

But the rest of this answer attempts to consider these caveats.但是这个答案的其余部分试图考虑这些警告。

Longer, much more pedantic answer更长,更迂腐的答案

Available since Python 3.4, use the new Path object in pathlib .从 Python 3.4 开始可用,使用pathlib中的新Path对象。 Note that .exists is not quite right, because directories are not files (except in the unix sense that everything is a file).请注意, .exists并不完全正确,因为目录不是文件(除非在 unix 意义上,一切都是文件)。

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

So we need to use is_file :所以我们需要使用is_file

>>> root.is_file()
False

Here's the help on is_file :这是有关is_file的帮助:

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

So let's get a file that we know is a file:所以让我们得到一个我们知道是文件的文件:

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

By default, NamedTemporaryFile deletes the file when closed (and will automatically close when no more references exist to it).默认情况下, NamedTemporaryFile在关闭时删除文件(并在不再存在对它的引用时自动关闭)。

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

If you dig into the implementation , though, you'll see that is_file uses try :但是,如果您深入研究实现,您会发现is_file使用了try

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

Race Conditions: Why we like try比赛条件:为什么我们喜欢尝试

We like try because it avoids race conditions.我们喜欢try ,因为它避免了竞争条件。 With try , you simply attempt to read your file, expecting it to be there, and if not, you catch the exception and perform whatever fallback behavior makes sense.使用try ,您只需尝试读取您的文件,并期望它在那里,如果没有,您会捕获异常并执行任何有意义的回退行为。

If you want to check that a file exists before you attempt to read it, and you might be deleting it and then you might be using multiple threads or processes, or another program knows about that file and could delete it - you risk the chance of a race condition if you check it exists, because you are then racing to open it before its condition (its existence) changes.如果您想在尝试读取文件之前检查文件是否存在,并且您可能正在删除它,然后您可能正在使用多个线程或进程,或者另一个程序知道该文件并可以删除它 - 您可能会冒如果您检查它是否存在,则为竞争条件,因为您随后会在其条件(其存在)更改之前竞相打开它。

Race conditions are very hard to debug because there's a very small window in which they can cause your program to fail.竞态条件很难调试,因为有一个非常小的窗口可能会导致程序失败。

But if this is your motivation, you can get the value of a try statement by using the suppress context manager.但是,如果这是您的动机,您可以通过使用suppress上下文管理器来获得try语句的值。

Avoiding race conditions without a try statement: suppress在没有 try 语句的情况下避免竞争条件: suppress

Python 3.4 gives us the suppress context manager (previously the ignore context manager), which does semantically exactly the same thing in fewer lines, while also (at least superficially) meeting the original ask to avoid a try statement: Python 3.4 为我们提供了suppress上下文管理器(以前是ignore上下文管理器),它在语义上以更少的行数完成完全相同的事情,同时(至少在表面上)满足了避免使用try语句的原始要求:

from contextlib import suppress
from pathlib import Path

Usage:用法:

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

For earlier Pythons, you could roll your own suppress , but without a try will be more verbose than with.对于较早的 Python,您可以使用自己的suppress ,但不try会比 with 更冗长。 I do believe this actually is the only answer that doesn't use try at any level in the Python that can be applied to prior to Python 3.4 because it uses a context manager instead:我确实相信这实际上是唯一在 Python 3.4 之前不使用任何级别的try的答案,因为它使用了上下文管理器:

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

Perhaps easier with a try:尝试一下可能更容易:

from contextlib import contextmanager

@contextmanager
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass

Other options that don't meet the ask for "without try":其他不符合“无需尝试”要求的选项:

isfile文件

import os
os.path.isfile(path)

from the docs :来自文档

os.path.isfile(path)

Return True if path is an existing regular file.如果 path 是现有的常规文件,则返回 True。 This follows symbolic links, so both islink() and isfile() can be true for the same path.这遵循符号链接,因此islink()isfile()对于同一路径都可以为真。

But if you examine the source of this function, you'll see it actually does use a try statement:但是如果你检查这个函数的 源代码,你会发现它确实使用了一个 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

All it's doing is using the given path to see if it can get stats on it, catching OSError and then checking if it's a file if it didn't raise the exception.它所做的只是使用给定的路径来查看它是否可以获得统计信息,捕获OSError ,然后检查它是否是一个文件,如果它没有引发异常。

If you intend to do something with the file, I would suggest directly attempting it with a try-except to avoid a race condition:如果您打算对该文件执行某些操作,我建议您直接尝试使用 try-except 来避免竞争条件:

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

os.access操作系统访问

Available for Unix and Windows is os.access , but to use you must pass flags, and it does not differentiate between files and directories.可用于 Unix 和 Windows 的是os.access ,但要使用你必须传递标志,它不区分文件和目录。 This is more used to test if the real invoking user has access in an elevated privilege environment:这更用于测试真正的调用用户是否可以在提升的特权环境中访问:

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

It also suffers from the same race condition problems as isfile .它也遭受与isfile相同的竞争条件问题。 From the docs :文档

Note: Using access() to check if a user is authorized to eg open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it.注意:使用 access() 来检查用户是否被授权例如在使用 open() 实际打开文件之前打开文件会产生安全漏洞,因为用户可能会利用检查和打开文件之间的短时间间隔来操作它。 It's preferable to use EAFP techniques.最好使用 EAFP 技术。 For example:例如:

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

is better written as:最好写成:

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

Avoid using os.access .避免使用os.access It is a low level function that has more opportunities for user error than the higher level objects and functions discussed above.它是一个低级函数,比上面讨论的高级对象和函数有更多的用户错误机会。

Criticism of another answer:对另一个答案的批评:

Another answer says this about os.access :另一个答案是关于os.access

Personally, I prefer this one because under the hood, it calls native APIs (via "${PYTHON_SRC_DIR}/Modules/posixmodule.c"), but it also opens a gate for possible user errors, and it's not as Pythonic as other variants:就个人而言,我更喜欢这个,因为在底层,它调用原生 API(通过“${PYTHON_SRC_DIR}/Modules/posixmodule.c”),但它也为可能的用户错误打开了一扇大门,而且它不像其他变体那样 Pythonic :

This answer says it prefers a non-Pythonic, error-prone method, with no justification.这个答案说它更喜欢非 Pythonic、容易出错的方法,没有任何理由。 It seems to encourage users to use low-level APIs without understanding them.它似乎鼓励用户在不了解它们的情况下使用低级 API。

It also creates a context manager which, by unconditionally returning True , allows all Exceptions (including KeyboardInterrupt and SystemExit !) to pass silently, which is a good way to hide bugs.它还创建了一个上下文管理器,通过无条件返回True ,允许所有异常(包括KeyboardInterruptSystemExit !)静默通过,这是隐藏错误的好方法。

This seems to encourage users to adopt poor practices.这似乎鼓励用户采用不良做法。

Prefer the try statement.更喜欢 try 语句。 It's considered better style and avoids race conditions.它被认为是更好的风格并避免了竞争条件。

Don't take my word for it.不要相信我的话。 There's plenty of support for this theory.这个理论有很多支持。 Here's a couple:这是一对:

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!"

Importing os makes it easier to navigate and perform standard actions with your operating system.导入os可以更轻松地使用您的操作系统进行导航和执行标准操作。

For reference also see How to check whether a file exists using Python?另请参阅如何使用 Python 检查文件是否存在?

If you need high-level operations, use shutil .如果您需要高级操作,请使用shutil

Testing for files and folders with os.path.isfile() , os.path.isdir() and os.path.exists()使用os.path.isfile()os.path.isdir()os.path.exists()测试文件和文件夹

Assuming that the "path" is a valid path, this table shows what is returned by each function for files and folders:假设“路径”是有效路径,下表显示了每个函数为文件和文件夹返回的内容:

在此处输入图像描述

You can also test if a file is a certain type of file using os.path.splitext() to get the extension (if you don't already know it)您还可以使用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

TL;DR TL;博士
answer is: use the pathlib module答案是:使用pathlib模块


Pathlib is probably the most modern and convenient way for almost all of the file operations. Pathlib可能是几乎所有文件操作的最现代和最方便的方式。 For the existence of a file or a folder a single line of code is enough.对于文件文件夹的存在,一行代码就足够了。

from pathlib import Path

if Path("myfile.txt").exists(): # works for both file and folders
    # do your cool stuff...

The pathlib module was introduced in Python 3.4 , so you need to have Python 3.4+, this lib makes your life much easier while working with files and folders and it is pretty to use, here is more doc about it ( https://docs.python.org/3/library/pathlib.html ). pathlib模块是在Python 3.4中引入的,所以你需要有 Python 3.4+,这个 lib 让你在处理文件和文件夹时变得更轻松,而且它很好用,这里有更多关于它的文档( https://docs .python.org/3/library/pathlib.html )。

BTW, if you are going to reuse the path, then it is better to assign it to a variable顺便说一句,如果您要重用路径,那么最好将其分配给变量

so will become所以会变成

from pathlib import Path

p = Path("loc/of/myfile.txt")
if p.exists(): # works for both file and folders
    # do stuffs...
#reuse 'p' if needed.

In 2016 the best way is still using os.path.isfile :在 2016 年,最好的方法仍然是使用os.path.isfile

>>> os.path.isfile('/path/to/some/file.txt')

Or in Python 3 you can use pathlib :或者在 Python 3 中,您可以使用pathlib

import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
    ...

It doesn't seem like there's a meaningful functional difference between try/except and isfile() , so you should use which one makes sense. try/except 和isfile()之间似乎没有有意义的功能差异,所以你应该使用哪个有意义。

If you want to read a file, if it exists, do如果要读取文件,如果存在,请执行

try:
    f = open(filepath)
except IOError:
    print 'Oh dear.'

But if you just wanted to rename a file if it exists, and therefore don't need to open it, do但是,如果您只想重命名文件(如果存在),因此不需要打开它,请执行

if os.path.isfile(filepath):
    os.rename(filepath, filepath + '.old')

If you want to write to a file, if it doesn't exist, do如果要写入文件,如果文件不存在,请执行

# 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'

If you need file locking, that's a different matter.如果您需要文件锁定,那就另当别论了。

You could try this (safer):你可以试试这个(更安全):

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

The ouput would be:输出将是:

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

Then, depending on the result, your program can just keep running from there or you can code to stop it if you want.然后,根据结果,您的程序可以从那里继续运行,或者您可以根据需要编写代码来停止它。

Date:2017-12-04日期:2017-12-04

Every possible solution has been listed in other answers.每个可能的解决方案都已在其他答案中列出。

An intuitive and arguable way to check if a file exists is the following:检查文件是否存在的一种直观且有争议的方法如下:

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')

I made an exhaustive cheatsheet for your reference:我制作了一份详尽的备忘单供您参考:

#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']}

Although I always recommend using try and except statements, here are a few possibilities for you (my personal favourite is using os.access ):虽然我总是推荐使用tryexcept语句,但这里有一些可能性供您使用(我个人最喜欢使用os.access ):

  1. Try opening the file:尝试打开文件:

    Opening the file will always verify the existence of the file.打开文件将始终验证文件的存在。 You can make a function just like so:你可以像这样创建一个函数:

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

    If it's False, it will stop execution with an unhanded IOError or OSError in later versions of Python.如果为 False,它将在更高版本的 Python 中以未处理的 IOError 或 OSError 停止执行。 To catch the exception, you have to use a try except clause.要捕获异常,您必须使用 try except 子句。 Of course, you can always use a try except` statement like so (thanks to hsandt for making me think):当然,您总是可以像这样使用try except` 语句(感谢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. Use os.path.exists(path) :使用os.path.exists(path)

    This will check the existence of what you specify.这将检查您指定的内容是否存在。 However, it checks for files and directories so beware about how you use it.但是,它会检查文件目录,因此请注意您如何使用它。

     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. Use os.access(path, mode) :使用os.access(path, mode)

    This will check whether you have access to the file.这将检查您是否有权访问该文件。 It will check for permissions.它将检查权限。 Based on the os.py documentation, typing in os.F_OK , it will check the existence of the path.根据 os.py 文档,输入os.F_OK ,它将检查路径是否存在。 However, using this will create a security hole, as someone can attack your file using the time between checking the permissions and opening the file.但是,使用它会造成安全漏洞,因为有人可以使用检查权限和打开文件之间的时间来攻击您的文件。 You should instead go directly to opening the file instead of checking its permissions.您应该直接打开文件而不是检查其权限。 ( EAFP vs LBYP ). EAFPLBYP )。 If you're not going to open the file afterwards, and only checking its existence, then you can use this.如果您以后不打算打开文件,只检查它的存在,那么您可以使用它。

    Anyway, here:无论如何,这里:

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

I should also mention that there are two ways that you will not be able to verify the existence of a file.我还应该提到,有两种方法无法验证文件是否存在。 Either the issue will be permission denied or no such file or directory .问题将是permission deniedno such file or directory If you catch an IOError , set the IOError as e (like my first option), and then type in print(e.args) so that you can hopefully determine your issue.如果您发现IOError ,请将IOError as e (就像我的第一个选项一样),然后输入print(e.args)以便您可以确定您的问题。 I hope it helps!我希望它有帮助! :) :)

The easiest way to do this is with最简单的方法是使用

import os

if os.path.exists(FILE):
  # file exists
  pass
else:
  # file does not exists
  pass

from the os library, while FILE is the relative path.来自 os 库,而FILE是相对路径。 In Windows this may or many not work and you may have to use the absolution path by doing os.path.exists(os.path.join(os.path.abspath('./'), FILE)) , where FILE is still the relative path plus file name在 Windows 中,这可能或许多不起作用,您可能必须通过执行os.path.exists(os.path.join(os.path.abspath('./'), FILE))来使用绝对路径,其中FILE是仍然是相对路径加文件名

If the file is for opening you could use one of the following techniques:如果文件用于打开,您可以使用以下技术之一:

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!')

UPDATE更新

Just to avoid confusion and based on the answers I got, current answer finds either a file or a directory with the given name.只是为了避免混淆,根据我得到的答案,当前答案会找到具有给定名称的文件目录。

Additionally, os.access() :此外, os.access()

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

Being R_OK , W_OK , and X_OK the flags to test for permissions ( doc ).作为R_OKW_OKX_OK标志来测试权限( doc )。

You Can Use os.path.exists() :你可以使用 os.path.exists() :

import os
print(os.path.exists("file"))

Hope It Helps :D希望它有帮助:D

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

Raising exceptions is considered to be an acceptable, and Pythonic, approach for flow control in your program.引发异常被认为是一种可接受的 Pythonic 方法,用于在您的程序中进行流控制。 Consider handling missing files with IOErrors.考虑使用 IOErrors 处理丢失的文件。 In this situation, an IOError exception will be raised if the file exists but the user does not have read permissions.在这种情况下,如果文件存在但用户没有读取权限,则会引发 IOError 异常。

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

If you imported NumPy already for other purposes then there is no need to import other libraries like pathlib , os , paths , etc.如果您已经出于其他目的导入了 NumPy,则无需导入其他库,如pathlibospaths等。

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

This will return true or false based on its existence.这将根据其存在返回 true 或 false。

You can write Brian's suggestion without the try: .您无需try:

from contextlib import suppress

with suppress(IOError), open('filename'):
    process()

suppress is part of Python 3.4. suppress是 Python 3.4 的一部分。 In older releases you can quickly write your own suppress:在旧版本中,您可以快速编写自己的抑制:

from contextlib import contextmanager

@contextmanager
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass

Check file or directory exists检查文件或目录是否存在

You can follow these three ways:您可以遵循以下三种方式:

Note1: The os.path.isfile used only for files Note1: os.path.isfile仅用于文件

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

Note2: The os.path.exists used for both files and directories Note2: os.path.exists用于文件和目录

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

The pathlib.Path method (included in Python 3+, installable with pip for Python 2) pathlib.Path方法(包含在 Python 3+ 中,可通过 Python 2 的 pip 安装)

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

I'm the author of a package that's been around for about 10 years, and it has a function that addresses this question directly.我是一个已经存在了大约 10 年的包的作者,它具有直接解决这个问题的功能。 Basically, if you are on a non-Windows system, it uses Popen to access find .基本上,如果您在非 Windows 系统上,它使用Popen来访问find However, if you are on Windows, it replicates find with an efficient filesystem walker.但是,如果您在 Windows 上,它会使用高效的文件系统 walker 复制find

The code itself does not use a try block… except in determining the operating system and thus steering you to the "Unix"-style find or the hand-buillt find .代码本身不使用try块......除了确定操作系统并因此引导您使用“Unix”风格的find或手工构建的find Timing tests showed that the try was faster in determining the OS, so I did use one there (but nowhere else).计时测试表明,该try在确定操作系统方面更快,所以我确实在那里使用了一个(但在其他地方没有)。

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

And the doc…还有医生……

>>> print pox.find.__doc__
find(patterns[,root,recurse,type]); Get path to a file or directory

    patterns: name or partial name string of items to search for
    root: path string of top-level directory to search
    recurse: if True, recurse down from root directory
    type: item filter; one of {None, file, dir, link, socket, block, char}
    verbose: if True, be a little verbose about the search

    On 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']

>>>

The implementation, if you care to look, is here: https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190如果你想看的话,实现在这里: https ://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190

Adding one more slight variation which isn't exactly reflected in the other answers.添加一个未完全反映在其他答案中的细微变化。

This will handle the case of the file_path being None or empty string.这将处理file_pathNone或空字符串的情况。

def file_exists(file_path):
    if not file_path:
        return False
    elif not os.path.isfile(file_path):
        return False
    else:
        return True

Adding a variant based on suggestion from Shahbaz根据 Shahbaz 的建议添加变体

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

Adding a variant based on suggestion from Peter Wood根据 Peter Wood 的建议添加变体

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

Here's a 1 line Python command for the Linux command line environment.这是用于 Linux 命令行环境的 1 行 Python 命令。 I find this VERY HANDY since I'm not such a hot Bash guy.我觉得这很方便,因为我不是那么热的 Bash 人。

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

I hope this is helpful.我希望这是有帮助的。

You can use the "OS" library of Python:您可以使用 Python 的“OS”库:

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

How do I check whether a file exists, without using the try statement?如何在不使用 try 语句的情况下检查文件是否存在?

In 2016, this is still arguably the easiest way to check if both a file exists and if it is a file:在 2016 年,这仍然可以说是检查文件是否存在以及它是否是文件的最简单方法:

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

isfile is actually just a helper method that internally uses os.stat and stat.S_ISREG(mode) underneath. isfile实际上只是一个辅助方法,它在内部使用os.statstat.S_ISREG(mode) This os.stat is a lower-level method that will provide you with detailed information about files, directories, sockets, buffers, and more.这个os.stat是一个较低级别的方法,它将为您提供有关文件、目录、套接字、缓冲区等的详细信息。 More about os.stat here更多关于 os.stat 这里

Note: However, this approach will not lock the file in any way and therefore your code can become vulnerable to " time of check to time of use " ( TOCTTOU ) bugs.注意:但是,这种方法不会以任何方式锁定文件,因此您的代码可能容易受到“检查时间到使用时间”( TOCTTOU )错误的影响。

So raising exceptions is considered to be an acceptable, and Pythonic, approach for flow control in your program.因此,引发异常被认为是一种可接受的 Pythonic 方法,用于在您的程序中进行流控制。 And one should consider handling missing files with IOErrors, rather than if statements ( just an advice ).并且应该考虑使用 IOErrors 处理丢失的文件,而不是if语句(只是一个建议)。

import os.path

def isReadableFile(file_path, file_name):
    full_path = file_path + "/" + file_name
    try:
        if not os.path.exists(file_path):
            print "File path is invalid."
            return False
        elif not os.path.isfile(full_path):
            print "File does not exist."
            return False
        elif not os.access(full_path, os.R_OK):
            print "File cannot be read."
            return False
        else:
            print "File can be read."
            return True
    except 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)

exists() and is_file() methods of ' Path ' object can be used for checking if a given path exists and is a file. ' Path ' 对象的exists()is_file()方法可用于检查给定路径是否存在并且是文件。

Python 3 program to check if a file exists:用于检查文件是否存在的 Python 3 程序:

# File name:  check-if-file-exists.py

from pathlib import Path

filePath = Path(input("Enter path of the file to be found: "))

if filePath.exists() and filePath.is_file():
    print("Success: File exists")
else:
    print("Error: File does not exist")

Output:输出:

$ python3 check-if-file-exists.py $ python3 检查文件是否存在.py

Enter path of the file to be found: /Users/macuser1/stack-overflow/index.html输入要找到的文件的路径: /Users/macuser1/stack-overflow/index.html

Success: File exists成功:文件存在

$ python3 check-if-file-exists.py $ python3 检查文件是否存在.py

Enter path of the file to be found: hghjg jghj输入要查找的文件路径: hghjg jghj

Error: File does not exist错误:文件不存在

Use os.path.exists() to check whether file exists or not:使用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..')
import os
path = /path/to/dir

root,dirs,files = os.walk(path).next()
if myfile in files:
   print "yes it exists"

This is helpful when checking for several files.这在检查多个文件时很有帮助。 Or you want to do a set intersection/ subtraction with an existing list.或者您想对现有列表进行设置交集/减法。

You should definitely use this one.你绝对应该使用这个。

from os.path import exists

if exists("file") == True:
    print "File exists."
elif exists("file") == False:
    print "File doesn't exist."

You can use the following open method to check if a file exists + readable:您可以使用以下打开方法来检查文件是否存在+可读:

file = open(inputFile, 'r')
file.close()

To check if a file exists,要检查文件是否存在,

from sys import argv

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

You can use os.listdir to check if a file is in a certain directory.您可以使用 os.listdir 检查文件是否在某个目录中。

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

# for testing purpose args defaulted to current folder & 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))

Basically a folder check, then a file check with proper directory separator using os.path.join .基本上是文件夹检查,然后使用os.path.join使用适当的目录分隔符进行文件检查。

Another possible option is to check whether the filename is in the directory using os.listdir()另一种可能的选择是使用 os.listdir() 检查文件名是否在目录中

import os
if 'foo.txt' in os.listdir():
    # Do things

this will return true if it is and false if not如果是则返回 true,否则返回 false

from os import path as fp

a = fp.isfile(r"Path/To/Your/File/And/File.Extension")
if a==True:
    print("File Exists")
else:
    print("File Doesn't Exist")

b = fp.exists("Path/To/Your/File/")
if b==True:
    print("Path Exists")
else:
    print("Path Doesn't Exist")

It's really simple if you think about it.如果你仔细想想,这真的很简单。 All the given answers contribute to something, but your question stated that it should not have "try" statement.所有给出的答案都有助于某事,但您的问题表明它不应该有“try”语句。 It requires only the os module and is easy to implement also, the try/except are overused these days.它只需要 os 模块并且也很容易实现,现在 try/except 被过度使用了。 This also depends on where do you want to use this code/ for what purpose.这也取决于您想在哪里使用此代码/用于什么目的。 If you are writing a complex code or want to browse a directory, this is not what you are looking for.如果您正在编写复杂的代码或想要浏览目录,这不是您要找的。 Please state the purpose of your code to make answers more customized.请说明您的代码的用途,以使答案更加个性化。

This is how i found a list of files(in this images) in one folder and searched it in a folder (with subfolders)这就是我如何在一个文件夹中找到文件列表(在此图像中)并在文件夹中搜索它(带有子文件夹)

# This script concatenates javascript files into a unified js to reduce server round-trips

import os
import string
import math
import ntpath
import sys

#import pyodbc

import gzip
import shutil

import hashlib

# BUF_SIZE is totally arbitrary, change for your app!
BUF_SIZE = 65536  # lets read stuff in 64kb chunks

# Iterate over all js files in the folder and combine them
filenames = []
shortfilenames = []

imgfilenames = []
imgshortfilenames = []

#Get a unified path so we can stop dancing with user paths
# Determine where files are on this machine (%TEMP% dir and app installation dir)
if '.exe' in sys.argv[0]: # if getattr(sys, 'frozen', False):
    RootPath = os.path.abspath(os.path.join(__file__, "..\\"))
   

elif __file__:
    RootPath = os.path.abspath(os.path.join(__file__, "..\\"))
 
print ("\n storage of image files RootPath: %s\n" %RootPath)


FolderPath = "D:\\TFS-FARM1\\StoneSoup_STS\\SDLC\\Build\\Code\\StoneSoup_Refactor\\StoneSoupUI\\Images"
print ("\n storage of image files in folder to search: %s\n" %FolderPath)


for root, directories, filenames2 in os.walk(FolderPath):
    for filename in filenames2:
        fullname = os.path.join(root, filename)        
        filenames.append(fullname)
        shortfilenames.append(filename)        

for i, fname in enumerate(shortfilenames):        
        print("%s - %s" % (i+1, fname))

for root, directories, filenames2 in os.walk(RootPath):
    for filename in filenames2:
        fullname = os.path.join(root, filename)        
        imgfilenames.append(fullname)
        imgshortfilenames.append(filename)        

for i, fname in enumerate(imgshortfilenames):        
        print("%s - %s" % (i+1, fname))
        
for i, fname in enumerate(imgshortfilenames):
        if fname in shortfilenames:
            print("%s - %s exists" % (i+1, fname))
        else:
            print("%s - %s ABSENT" % (i+1, fname))

Use the following code:使用以下代码:

def findfile(filepath):
  flag = False

  for filename in os.listdir(filepath)
    if filename == "your file name":
      flag = True
      break
    else:
      print("no file found")
  if flag == True:
    return True
  else:
    return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM