如何检查是否存在文件,而不使用试用声明?
当前回答
>>> from pathlib import Path
>>> Path('/').is_file()
False
>>> Path('/initrd.img').is_file()
True
>>> Path('/doesnotexist').is_file()
False
>>> import os
>>> os.path.isfile('/')
False
>>> os.path.isfile('/initrd.img')
True
>>> os.path.isfile('/doesnotexist')
False
现在上面的可能是最好的实用直接答案在这里,但有可能有一个竞赛条件(取决于你正在尝试实现什么),并且事实上,基础实施使用一个尝试,但Python使用尝试到处在其实施。
更长、更有趣的答案
>>> from pathlib import Path
>>> root = Path('/')
>>> root.exists()
True
>>> root.is_file()
False
is_file(self)
Whether this path is a regular file (also True for symlinks pointing
to regular files).
>>> import tempfile
>>> file = tempfile.NamedTemporaryFile()
>>> filepathobj = Path(file.name)
>>> filepathobj.is_file()
True
>>> filepathobj.exists()
True
>>> del file
>>> filepathobj.exists()
False
>>> filepathobj.is_file()
False
def is_file(self):
"""
Whether this path is a regular file (also True for symlinks pointing
to regular files).
"""
try:
return S_ISREG(self.stat().st_mode)
except OSError as e:
if e.errno not in (ENOENT, ENOTDIR):
raise
# Path doesn't exist or is a broken symlink
# (see https://bitbucket.org/pitrou/pathlib/issue/12/)
return False
from contextlib import suppress
from pathlib import Path
>>> with suppress(OSError), Path('doesnotexist').open() as f:
... for line in f:
... print(line)
...
>>>
>>> with suppress(OSError):
... Path('doesnotexist').unlink()
...
>>>
class suppress(object):
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
return issubclass(exc_type, self.exceptions)
from contextlib import contextmanager
@contextmanager
def suppress(*exceptions):
try:
yield
except exceptions:
pass
import os
os.path.isfile(path)
>>> OSError is os.error
True
try:
with open(path) as f:
f.read()
except OSError:
pass
import os
os.access(path, os.F_OK)
批评另一个答案:
另一个答案是关于os.access:
这个答案说,它更喜欢一个非皮顿,错误的方法,没有理由,似乎鼓励用户使用低级的API,而不理解它们。
它还创建了一个背景管理器,通过无条件返回真相,允许所有例外(包括键盘中断和系统输出!)沉默地通过,这是一个很好的方式来隐藏错误。
其他回答
此外, os.access():
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
是 R_OK, W_OK, 和 X_OK 旗帜测试许可证(doc)。
日期: 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']}
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作为一个插槽来执行盾牌命令:
底线:
使用 os.path.exist 查看文件和目录:
import os.path
os.path.exists(file_path)
使用 os.path.isfile 仅查看文件(注:以下是符号链接):
os.path.isfile(file_path)
使用:
import os
# For testing purposes the arguments defaulted to the current folder and file.
# returns True if file found
def file_exists(FOLDER_PATH='../', FILE_NAME=__file__):
return os.path.isdir(FOLDER_PATH) \
and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))
它基本上是一个文件夹检查,然后使用 os.path.join 使用适当的目录分离器进行文件检查。
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?