Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a directory contains a file with a given extension

I need to check the current directory and see if a file with an extension exists. My setup will (usually) only have one file with this extension. I need to check if that file exists, and if it does, run a command.

However, it runs the else multiple times because there are multiple files with alternate extensions. It must only run the else if the file does not exist, not once for every other file. My code sample is below.


The directory is structured like so:

dir_________________________________________
    \            \            \            \     
 file.false    file.false    file.true    file.false

When I run:

import os
for File in os.listdir("."):
    if File.endswith(".true"):
        print("true")
    else:
        print("false")

The output is:

false
false
true
false

The issue with this is if I replaced print("false") with something useful, it will run it multiple times.

Edit: I asked this question 2 years ago, and it's still seeing very mild activity, therefore, I'd like to leave this here for other people: http://book.pythontips.com/en/latest/for_-_else.html#else-clause

like image 499
Jacob Birkett Avatar asked Oct 28 '15 20:10

Jacob Birkett


People also ask

How would you search a file directory by extension?

To find all files with a file extension, write out its path to find a command with the options and expression specifying the extension. In the below-given example, we will find all files with the “. txt” extension. “.” in this command denotes that this tool will find all the “.

How do I get the file extension of a directory in Python?

We can use Python os module splitext() function to get the file extension. This function splits the file path into a tuple having two values - root and extension.


3 Answers

You can use the else block of the for:

for fname in os.listdir('.'):
    if fname.endswith('.true'):
        # do stuff on the file
        break
else:
    # do stuff if a file .true doesn't exist.

The else attached to a for will be run whenever the break inside the loop is not executed. If you think a for loop as a way to search something, then break tells whether you have found that something. The else is run when you didn't found what you were searching for.

Alternatively:

if not any(fname.endswith('.true') for fname in os.listdir('.')):
    # do stuff if a file .true doesn't exist

Moreover you could use the glob module instead of listdir:

import glob
# stuff
if not glob.glob('*.true')`:
    # do stuff if no file ending in .true exists
like image 121
Bakuriu Avatar answered Oct 24 '22 00:10

Bakuriu


If you only want to check that any file ends with a particular extension, use any.

import os
if any(File.endswith(".true") for File in os.listdir(".")):
    print("true")
else:
    print("false")
like image 20
Kevin Avatar answered Oct 23 '22 23:10

Kevin


You should use the glob module to look for exactly the files that you're interested in:

import glob

fileList = glob.glob("*.true")
for trueFile in fileList:
    doSomethingWithFile(trueFile)
like image 7
bgporter Avatar answered Oct 24 '22 01:10

bgporter