首页 > 解决方案 > 如何检测文件是否存在于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)插入完整的文件名

谢谢 !

标签: pythonfiledetect

解决方案


检查特定文件是否存在:

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')

推荐阅读