How to open a list of files in Python -
i'm reading data file (text), , generating number of reports, each 1 written different output file (also text). i'm opening them long way:
fp = open('file1','w')
invp = open('inventory','w')
orderp = open('orders','w')
... , on, corresponding group of close() lines @ end.
if open them loop, using list of fp names , file names, guarantee closing same files.
i tried using dictionary of fp:filename
, [obviously] didn't work, because either fp variable undefined, or string 'fp' isn't file object name.
since these output files, don't need check open errors - if can't open 1 or more, can't go on anyway.
is there way open group of files (not more 10 or so) list of names, in loop?
yes, can use list comprehension:
filenames = ['file1.txt', 'file2.txt', 'file3.txt'...] filedata = {filename: open(filename, 'w') filename in filenames}
now, of opened instances saved in filedata
, assigned name of file.
to close them:
for file in filedata.values(): file.close()