如何检查是否存在文件,而不使用试用声明?
当前回答
import os
if os.path.isfile(filepath):
print("File exists")
其他回答
如果文件是要打开的,您可以使用以下技术之一:
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!')
注意:此查找一个文件或指定的名称的目录。
我是包的作者,已经在周围约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
import os
if os.path.isfile(filepath):
print("File exists")
虽然我总是建议使用尝试和除陈述,这里有几个选项为您(我的个人喜爱是使用os.access):
尝试打开文件:打开文件将始终确认文件的存在. 你可以这样做一个函数: def File_Existence(filepath): f = open(filepath) return True 如果它是错误的,它将停止执行与未经处理的 IOError 或 OSError 在后续版本的 Python. 要捕获例外,你必须使用一个尝试,除了条款。
我还应该提到,有两种方式,你将无法验证一个文件的存在. 无论问题将被拒绝许可或没有这样的文件或目录. 如果你抓住一个IOError,设置IOError为e(如我的第一个选项),然后输入打印(e.args),以便你可以希望确定你的问题. 我希望它有助于! :)
如果你正在检查的原因是,所以你可以做一些类似的文件_存在: 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
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?