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
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 try: with open(filename, 'r') as file_handle: ... except IOError: break
Though this becomes pretty ugly with all the nesting. You're probably better off getting the list of filenames using something like
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.