0

I want to iterate through the filenames in a particular folder. I then wish to choose the first filename that satisfies a criteria (file name ends with '.txt')

Should I use a For loop and break it when I see the first file ending with .txt? Or should I use a While loop? The While loop does not seem to work. It keeps on continuing. It keeps on printing the filename as per below code.

Following is the code I am using:

import os
import pdb

asciipath = 'C:\\Users\\rmore\\Desktop\\Datalab'

x = 0

file = os.listdir(asciipath)

while file[x].endswith('.txt'):
    print(file[x])
    x = x+1
rmore911
  • 195
  • 2
  • 13
  • while loops and for loops are basically the same: iterate until happens. If your is "reached the end of a collection": then use a for loop. – JacobIRR Mar 22 '20 at 03:55

3 Answers3

2

It is possible to do this with a while loop, but it will overly complicate the code. I would use a for loop here. I would also rename file to files just to make what is happening a little more clear.

Edit:

As pointed out, an else clause for the loop would make for a

files = os.listdir(asciipath)

for file in files:
    if file.endswith('.txt'):
        print(file)
        break
else:
    print('No txt file found')

The break is key for stopping the loop after you find the first file that ends with .txt

Also note that the else statement is on the for loop and NOT inside of the loop. The else will only be triggered if the break statement is NOT triggered.

Community
  • 1
  • 1
Rashid 'Lee' Ibrahim
  • 1,357
  • 1
  • 9
  • 21
  • 1
    And perhaps an else: clause to catch no matches. – tdelaney Mar 22 '20 at 04:00
  • Thank you! I used to think 'Break'ing a For Loop is not recommended. But this method works. I will use this method. – rmore911 Mar 22 '20 at 04:10
  • @tdelaney good looking out. I added an else to the loop for if it's not broken out of – Rashid 'Lee' Ibrahim Mar 22 '20 at 04:14
  • @rmore911 breaks are used in production code all the time. They are a tool like everything else in programming. Not good or bad really. Even try-catch errors can be used as a tool for good things. It's all about code flow. Also, if the answer helped you, please mark it as accepted so others can see it works for the question. – Rashid 'Lee' Ibrahim Mar 22 '20 at 04:15
  • 1
    @rmore911 - This demonstrates a great use of `break`. You exit the loop when you get the information you want. But if the loop ends without a break, you fall into the else clause where you can have your error management code. We tend to forget the error cases and they give us sleepless nights later when everything goes bad. – tdelaney Mar 22 '20 at 04:23
  • thanks for pointing out the `break` idea! – Theo F Oct 31 '22 at 15:40
1

A pythonic way would be to use next on a generator:

next((f for f in file if f.endswith('.txt')), 'file not found')

Or you can loop over the files and return as soon as the condition is matched:

def find_first_txt_file(files)
    for file in files:
        if file.endswith('.txt'):
            return file
    return 'file not found'
Austin
  • 25,759
  • 4
  • 25
  • 48
1

Make it easier for yourself and use pathlib and glob.

from pathlib import Path
p = Path(asciipath)
print(next(p.glob('*.txt')))
David Nehme
  • 21,379
  • 8
  • 78
  • 117