【问题标题】:how to detect file if exist in python [duplicate]如何检测文件是否存在于python中[重复]
【发布时间】:2019-11-17 16:44:51
【问题描述】:

如何检测目录中是否存在特定文件? 例子: 我想检测目录(dir)中是否存在(.txt)文件 我试过这个:

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)插入完整的文件名

谢谢!

【问题讨论】:

  • 您已经在检查文件是否存在?是否要检查是否存在任何 .txt 文件?
  • 您没有使用绝对路径,因此仅测试给定文件名是否存在于当前工作目录中

标签: python file detect


【解决方案1】:
from glob import glob
files = glob('*.txt') 
print(len(files)) # will return the number of .txt files in the dir
print(files) # will return all the .txt files in the dir

【讨论】:

  • 这不会检查特定文件是否存在。
  • @DerekEden:我确实读过它。不要假设问题的英语是完美的。
  • 他的代码已经检查了特定文件,问题的第二部分说如果 .txt 文件...
  • 谢谢,这正是我想要的
【解决方案2】:

检查特定文件是否存在:

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

【讨论】:

    猜你喜欢
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 2012-01-25
    • 2011-10-17
    • 2020-02-04
    相关资源
    最近更新 更多