如何检查是否存在文件,而不使用试用声明?
当前回答
此外, os.access():
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
是 R_OK, W_OK, 和 X_OK 旗帜测试许可证(doc)。
其他回答
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
import os
path = /path/to/dir
root,dirs,files = os.walk(path).next()
if myfile in files:
print "yes it exists"
这在检查多个文件时是有用的,或者你想与现有列表进行一组交叉/分解。
要检查是否存在文件,
from sys import argv
from os.path import exists
script, filename = argv
target = open(filename)
print "file exists: %r" % exists(filename)
它似乎没有一个有意义的功能区别在尝试/排除和isfile(),所以你应该使用哪一个有意义。
如果你想阅读一个文件,如果它存在,
try:
f = open(filepath)
except IOError:
print 'Oh dear.'
但是,如果你只是想重新命名一个文件,如果它存在,因此不需要打开它,
if os.path.isfile(filepath):
os.rename(filepath, filepath + '.old')
如果你想写到文件,如果它不存在,
# Python 2
if not os.path.isfile(filepath):
f = open(filepath, 'w')
# Python 3: x opens for exclusive creation, failing if the file already exists
try:
f = open(filepath, 'wx')
except IOError:
print 'file already exists'
如果你需要文件锁,那是另一个问题。
这里是一个单线的Python命令为Linux命令线环境,我觉得这是非常有用的,因为我不是那么热的Bash男孩。
python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"
推荐文章
- 为什么我得到“'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锁定缓慢的测试