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


当前回答

查看文件或目录存在

你可以遵循这三种方式:

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

其他回答

添加一个更轻微的变化,这在其他答案中不完全反映。

这将处理文件_路径是无或空的字符串的情况。

此分類上一篇

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

添加基于Shahbaz的建议的变量

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

添加基于Peter Wood的建议的变量

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

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

如果文件是要打开的,您可以使用以下技术之一:

with open('somefile', 'xt') as f: # Using the x-flag, Python 3.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!')

注意:此查找一个文件或指定的名称的目录。

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

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

这就是我如何在一个文件夹中找到一个文件列表(在这些图像中)并在一个文件夹中搜索它(与子文件夹):

# This script concatenates JavaScript files into a unified JavaScript file 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  # Let’s read stuff in 64 kilobyte chunks

# Iterate over all JavaScript 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% directory and application installation directory)
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))