Breaking the loop properly in Python -
currently trying upload set of files via api call. files have sequential names: part0.xml, part1.xml, etc. loops through files , uploads them properly, seems doesn't break loop , after uploads last available file in directory getting error:
no such file or directory.
and don't understand how make stop last file in directory uploaded. dumb question, lost. how stop looping through non-existent files?
the code:
part = 0 open('part%d.xml' % part, 'rb') xml: #here goes api call code part +=1
i tried this:
import glob part = 0 fname in glob.glob('*.xml'): open('part%d.xml' % part, 'rb') xml: #here goes api call code part += 1
edit: thank answers, learned lot. still lots learn. :)
your for
loop saying "for every file ends .xml
"; if have file ends .xml
isn't sequential part%d.xml
, you're going error. imagine have part0.xml
, foo.xml
. for
loop going loop twice; on second loop, it's going try open part1.xml
, doesn't exist.
since know filenames already, don't need use glob.glob()
; check if each file exists before opening it, until find 1 doesn't exist.
import os itertools import count filenames = ('part%d.xml' % part_num part_num in count()) filename in filenames: if os.path.exists(filename): open(filename, 'rb') xmlfile: do_stuff(xml_file) # here goes api call code else: break
if reason you're worried files disappearing between os.path.exists(filename)
, open(filename, 'rb')
, code more robust:
import os itertools import count filenames = ('part%d.xml' % part_num part_num in count()) filename in filenames: try: xmlfile = open(filename, 'rb') except ioerror: break else: xmlfile: do_stuff(xmlfile) # here goes api call code
Comments
Post a Comment