如何检查是否存在文件,而不使用试用声明?
当前回答
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作为一个插槽来执行盾牌命令:
底线:
其他回答
我是包的作者,已经在周围约10年,它有一个功能,直接解决这个问题. 基本上,如果你在一个非Windows系统,它使用Popen访问找到。
代码本身不使用试区块......除非确定操作系统,从而引导你到“Unix”风格的搜索或手建的搜索,时间测试表明,试图更快地确定操作系统,所以我使用其中一个(但没有其他地方)。
>>> import pox
>>> pox.find('*python*', type='file', root=pox.homedir(), recurse=False)
['/Users/mmckerns/.python']
而博士......
>>> print pox.find.__doc__
find(patterns[,root,recurse,type]); Get path to a file or directory
patterns: name or partial name string of items to search for
root: path string of top-level directory to search
recurse: if True, recurse down from root directory
type: item filter; one of {None, file, dir, link, socket, block, char}
verbose: if True, be a little verbose about the search
On some OS, recursion can be specified by recursion depth (an integer).
patterns can be specified with basic pattern matching. Additionally,
multiple patterns can be specified by splitting patterns with a ';'
For example:
>>> find('pox*', root='..')
['/Users/foo/pox/pox', '/Users/foo/pox/scripts/pox_launcher.py']
>>> find('*shutils*;*init*')
['/Users/foo/pox/pox/shutils.py', '/Users/foo/pox/pox/__init__.py']
>>>
實施,如果你想看,在這裡: https://github.com/uqfoundation/pox/blob/89f90fb308f285ca7a62eabe2c38acb87e89dad9/pox/shutils.py#L190
你可以尝试一下(更安全):
try:
# http://effbot.org/zone/python-with-statement.htm
# 'with' is safer to open a file
with open('whatever.txt') as fh:
# Do something with 'fh'
except IOError as e:
print("({})".format(e))
奥普特将是:
(没有此类文件或目录:‘whatever.txt’)
然后,取决于结果,你的程序可以只是从那里继续运行,或者你可以编码阻止它,如果你愿意。
您可以使用以下开放方法检查是否存在 + 可阅读的文件:
file = open(inputFile, 'r')
file.close()
在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():
...
查看文件或目录存在
你可以遵循这三种方式:
使用 isfile( )
注意1: os.path.isfile 仅用于文件
import os.path
os.path.isfile(filename) # True if file exists
os.path.isfile(dirname) # False if directory exists
二、使用存在
注意2: os.path.exists 用于文件和目录
import os.path
os.path.exists(filename) # True if file exists
os.path.exists(dirname) # True if directory exists
pathlib.Path 方法(包含在 Python 3+ 中,可与 Python 2 的 pip 安装)
from pathlib import Path
Path(filename).exists()
推荐文章
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试