如何检查是否存在文件,而不使用试用声明?
当前回答
使用 os.path.exists() 查看是否存在文件:
def fileAtLocation(filename,path):
return os.path.exists(path + filename)
filename="dummy.txt"
path = "/home/ie/SachinSaga/scripts/subscription_unit_reader_file/"
if fileAtLocation(filename,path):
print('file found at location..')
else:
print('file not found at location..')
其他回答
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
另一个可能的选项是检查文件名是否在目录中使用 os.listdir():
import os
if 'foo.txt' in os.listdir():
# Do things
如果是真相,如果是虚假,如果不是真相。
添加一个更轻微的变化,这在其他答案中不完全反映。
这将处理文件_路径是无或空的字符串的情况。
此分類上一篇
def file_exists(file_path):
if not file_path:
return False
elif not os.path.isfile(file_path):
return False
else:
return True
添加基于Shahbaz的建议的变量
def file_exists(file_path):
if not file_path:
return False
else:
return os.path.isfile(file_path)
添加基于Peter Wood的建议的变量
def file_exists(file_path):
return file_path and os.path.isfile(file_path):
import os
if os.path.isfile(filepath):
print("File exists")
您可以使用Python的“OS”图书馆:
>>> import os
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.txt")
True
>>> os.path.exists("C:\\Users\\####\\Desktop\\test.tx")
False
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?