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


当前回答

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

if os.path.isfile(filepath):
   print("File 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):

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 错误: 文件不存在

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

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