如何检查是否存在文件,而不使用试用声明?
当前回答
在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():
...
其他回答
此外, os.access():
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
是 R_OK, W_OK, 和 X_OK 旗帜测试许可证(doc)。
这就是我如何在一个文件夹中找到一个文件列表(在这些图像中)并在一个文件夹中搜索它(与子文件夹):
# 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))
添加一个更轻微的变化,这在其他答案中不完全反映。
这将处理文件_路径是无或空的字符串的情况。
此分類上一篇
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):
os.path - posixpath.py (ntpath.py) genericpath.py - 行 ~20+ def exists(path): ""“测试是否有一条路径存在. Returns False for broken symbolic links”"" try: st = os.stat(path) except os.error: return False return True
或:
3、文件系统跨功能
因为这些在文件夹上,(在大多数情况下)它们对我们的问题是无效的(有例外,如非野卡的全球化 - 如 @ShadowRanger指出),所以我不会坚持它们。
os.access("/tmp", os.F_OK)
Linux(Ubuntu(维基百科:Ubuntu版史) 16 x86_64 (pc064)) 也相当于:
笔记:
但是,因为这更像一个工人,我在这里停下来。
6、SysAdmin方法
我认为这是一个(Lame)工作室(gainarie):使用Python作为一个插槽来执行盾牌命令:
底线:
如何检查是否存在文件,而不使用试用声明?
在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,而不是如果声明(只是一个建议)。