简体   繁体   中英

How to add many codecs.open to ' for ' loop

I need these lines to go in ' for ' loop to shorten the whole module.

peanut = codecs.open("butter.txt", mode="w")
duck = codecs.open("tape.txt", mode="w")
hair = codecs.open("style.txt", mode="w")
italy = codecs.open("spaghetti.txt", mode="w")
smile = codecs.open("cheese.txt", mode="w")

Something like:

for five_txt in peanut, duck, hair, italy, smile:
    codecs.open()

Put the filenames into a list and iterate through it.

filenames = ["butter.txt", 
    "tape.txt", 
    "style.txt", 
    "spaghetti.txt", 
    "cheese.txt"]

for fname in filenames:
    fhandler = codecs.open(fname, mode="w")
a_list = [peanut, duck, hair, italy, smile]
for elem in a_list:
    opened_file = codecs.open(elem, mode="w")
inst_dict = {}
for file in [('butter.txt', 'peanut'), ('tape.txt', 'duck'), ('style.txt', 'hair'), ('spaghetti.txt', 'italy'), ('cheese.txt','style')]:
    inst_dict[file[1]] = codecs.open(file[0], mode='w')

You can now also access the instances from the dictionary like:

inst_dict['peanut']
inst_dict['duck']
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM