如何检查是否存在文件,而不使用试用声明?
当前回答
日期: 2017-12-04
每個可能的解決方案都被列入其他答案中。
一个直观和可争议的方式来检查是否存在文件是如下:
import os
os.path.isfile('~/file.md') # Returns True if exists, else False
# Additionally, check a directory
os.path.isdir('~/folder') # Returns True if the folder exists, else False
# Check either a directory or a file
os.path.exists('~/file')
我为您的参考做了一个完整的骗局:
# os.path methods in exhaustive cheat sheet
{'definition': ['dirname',
'basename',
'abspath',
'relpath',
'commonpath',
'normpath',
'realpath'],
'operation': ['split', 'splitdrive', 'splitext',
'join', 'normcase'],
'compare': ['samefile', 'sameopenfile', 'samestat'],
'condition': ['isdir',
'isfile',
'exists',
'lexists'
'islink',
'isabs',
'ismount',],
'expand': ['expanduser',
'expandvars'],
'stat': ['getatime', 'getctime', 'getmtime',
'getsize']}
其他回答
这里是一个单线的Python命令为Linux命令线环境,我觉得这是非常有用的,因为我不是那么热的Bash男孩。
python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"
如果你正在检查的原因是,所以你可以做一些类似的文件_存在: 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
import os
path = /path/to/dir
root,dirs,files = os.walk(path).next()
if myfile in files:
print "yes it exists"
这在检查多个文件时是有用的,或者你想与现有列表进行一组交叉/分解。
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作为一个插槽来执行盾牌命令:
底线:
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