python - opening several txt files using while loop -
i have txt files names have following pattern:
arc.1.txt, arc.2.txt,...,arc.100.txt,..., arc.500.txt,...,arc.838.txt i know can write program using for loop open files 1 one, if total numbers of files. want know possible use while loop without counting number files open them ?
it possible use while loop assuming files numbered in sequential order:
i = 0 while true: += 1 filename = 'arc.%d.txt' % try: open(filename, 'r') file_handle: ... except ioerror: break though becomes pretty ugly nesting. you're better off getting list of filenames using glob.glob.
from glob import glob filenames = glob('arc.*.txt') filename in filenames: open(filename) file_handle: ... there race conditions associated second approach -- if file somehow gets deleted between when glob found , when time process file program have bad day.
Comments
Post a Comment