39

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

0

5 Answers 5

50

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
1
  • 2
    with the new pathlib library, you can change glob to if not list(pathlib.Path(".").rglob("*.true"))
    – Sylvain
    Jun 25, 2020 at 18:34
22

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")
8

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

Similar to @bgporter's solution, you could also use Path to do something similar:

from pathlib import Path
cwd = Path.cwd()
for path in cwd.glob("*.true"):
   print("true")
   DoSomething(path)
2
  • do you mean from pathlib import Path by import Path? Jan 18, 2023 at 15:33
  • Yes that's right, just corrected that, thanks for spotting that. @SardarFaisal Jan 18, 2023 at 16:02
0

Alternative if you want to use the same logic you can try to use a flag that turns on only if the file does not exist. Then use an if to run the not exist script.

import os 

for File in os.listdir("."): 
    if File.endswith(".true"):
        print("true") 
    else:
      flag=True
 
if flag:
  # -your code-
2
  • This is a useful answer because a reader may learn to use this technique in other circumstances. It also would work in all languages. A disadvantage is that it continues to run the loop, even if flag has already been found. One might rectify this with a break after setting the flag. Mar 21 at 21:20
  • As another note, flag ought to be initialized. I don't remember Python's treatment of uninitialized values, but even if it treats them falsey, it is best to initialize for clarity. Mar 21 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.