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


当前回答

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

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

其他回答

如果您已经进口了NumPy用于其他用途,那么不需要进口其他图书馆,如Pathlib,OS,路径等。

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

这将根据它的存在返回真实或虚假。

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

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

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:
    with p.open() as f:
        # do awesome stuff
except OSError:
    print('Well darn.')

pathlib 模块有很多很好的东西在它:方便的旋转,检查文件的所有者,更容易的路径加入,等等,值得检查。 如果你在更老的 Python (版本 2.6 或更晚),你仍然可以安装 pathlib 带 pip:

# 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

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

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

此分類上一篇

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

exist() and is_file() 对“路”对象的方法可以用来检查是否有一个特定的路径存在并是一个文件。

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

出口:

$ python3 check-if-file-exists.py 输入文件的路径可以找到: /Users/macuser1/stack-overflow/index.html 成功: 文件存在 $ python3 check-if-file-exists.py 输入文件的路径可以找到: hghjg jghj 错误: 文件不存在