如何检查是否存在文件,而不使用试用声明?
当前回答
使用 os.path.isfile(), os.path.isdir() 和 os.path.exists() 的文件和文件夹进行测试
假设“路径”是有效的路径,此表显示了每个函数为文件和文件夹返回的内容:
此分類上一篇
您还可以测试文件是否是一种特定类型的文件,使用 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
其他回答
如果你正在检查的原因是,所以你可以做一些类似的文件_存在: open_it(),它更安全地使用一个尝试周围试图打开它。
如果您不打算立即打开文件,您可以使用 os.path.isfile。
如果路径是现有常规文件,则返回是真实的,这跟随了象征性链接,因此 islink() 和 isfile() 都可以对同一条路径是真实的。
import os.path
os.path.isfile(fname)
如果你需要确保它是一个文件。
从 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
要查看一个目录,请:
if my_file.is_dir():
# directory exists
要检查路径对象是否存在,无论它是否是一个文件或目录,使用存在():
if my_file.exists():
# path exists
您也可以在尝试区块中使用 resolve(strict=True):
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
使用 os.path.exist 查看文件和目录:
import os.path
os.path.exists(file_path)
使用 os.path.isfile 仅查看文件(注:以下是符号链接):
os.path.isfile(file_path)
如果文件是要打开的,您可以使用以下技术之一:
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!')
注意:此查找一个文件或指定的名称的目录。
这就是我如何在一个文件夹中找到一个文件列表(在这些图像中)并在一个文件夹中搜索它(与子文件夹):
# 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))
不同于 isfile(), exist() 将返回 True for Directory. 因此,根据您是否只需要平板文件或 Directory,您将使用 isfile() 或 exist()。 这里有一些简单的 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