[英]How to add many codecs.open to ' for ' loop
我需要这些行进入'for'循环以缩短整个模块。
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")
就像是:
for five_txt in peanut, duck, hair, italy, smile:
codecs.open()
将文件名放入列表中并进行遍历。
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')
现在,您还可以从字典中访问实例,例如:
inst_dict['peanut']
inst_dict['duck']
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.