python - 如何检测文件是否存在于python中
问题描述
如何检测目录中是否存在特定文件?示例:我想检测(.txt)文件是否存在于我尝试过的目录(dir)中:
import os.path
from os import path
def main():
print ("file exist:"+str(path.exists('guru99.txt')))
print ("File exists:" + str(path.exists('career.guru99.txt')))
print ("directory exists:" + str(path.exists('myDirectory')))
if __name__== "__main__":
main()
但是所有这些功能都必须使用格式(.txt)插入完整的文件名
谢谢 !
解决方案
检查特定文件是否存在:
import os
os.path.exists(path_to_file)
如果存在则返回 True,否则返回 False
检查是否存在任何 .txt 文件:
import glob
if glob.glob(path_to_files_'*.txt'):
print('exists')
else:
print('doesnt')
推荐阅读
- java - 有没有一种干净的方法来更改 Nimbus Jose JWT 中的默认 JWKSetCache TTL?
- amazon-web-services - AWS 数据库子网为空
- r - 如何重命名文件以使文件扩展名不出现在使用 R 的名称中
- javascript - VueJS 不在电子应用程序内的 DOM 上呈现数据
- javascript - 无法读取 null 的属性“classList”
- python - 如何正确安装 virtualenv 和 virtualenvwrapper?
- c++ - Boost bootstrap 抛出错误
- python - 在 matplotlib 散点图中自定义 x 和 y 标签
- c# - 如何为 EF 6.4 和 MySQL C# 启用迁移?
- r - ANOVA 模型中的“+”与“*”有什么区别?