-3

how can i detect if a specifics files exist in directory ? example: i want to detect if (.txt) files exist in directory (dir) i tried with this :

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

but all this functions you must to insert the complete file name with format(.txt)

Thank you !

2 Answers2

1

to check if a specific file exists:

import os
os.path.exists(path_to_file)

will return True if it exists, False if not

to check if ANY .txt files exist:

import glob
    if glob.glob(path_to_files_'*.txt'):
        print('exists')
    else:
        print('doesnt')
Derek Eden
  • 4,403
  • 3
  • 18
  • 31
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
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143