Mary Mary - 1 month ago 4
Python Question

opening several txt file using while loop

I have some txt files that their names have the following pattern:

arc.1.txt, arc.2.txt,...,arc.100.txt,..., arc.500.txt,...,arc.838.txt

I know that we can write a program using
for loop
to open the files one by one, if we now the total numbers of files. I want to know is it possible to use
While loop
without counting the number files to open them ?


It is definitely possible to use a while loop assuming that the files are numbered in sequential order:

i = 0
while True:
    i += 1
    filename = 'arc.%d.txt' % i
        with open(filename, 'r') as file_handle:
    except IOError:

Though this becomes pretty ugly with all the nesting. You're probably better off getting the list of filenames using something like glob.glob.

from glob import glob
filenames = glob('arc.*.txt')
for filename in filenames:
    with open(filename) as file_handle:

There are some race conditions associated with this second approach -- If the file somehow gets deleted between when glob found it and when it actually is time to process the file then your program could have a bad day.