Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I find whether there is any txt file in a directory or not with Python

I would like to find that whether there is any file exists in a specific directory or not with using python.

Something like this;

if os.path.exists('*.txt'):
   # true --> do something
else:
   # false --> do something
like image 834
erolkaya84 Avatar asked Mar 01 '14 11:03

erolkaya84


People also ask

How can I tell if a text file exists?

To check if a file exists, you pass the file path to the exists() function from the os. path standard library. If the file exists, the exists() function returns True . Otherwise, it returns False .


1 Answers

You can use glob.glob with wildcards and check whether it returns anything. For instance:

import glob
if glob.glob('*.txt'):
    # file(s) exist -> do something
else:
    # no files found

Note that glob.glob return a list of files matching the wildcard (or an empty list).

like image 195
isedev Avatar answered Sep 29 '22 23:09

isedev