如何在'for'循环中添加许多codecs.open

时间:2013-09-12 06:27:19

标签: python

我需要这些行进入'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()

3 个答案:

答案 0 :(得分:2)

将文件名放入列表并迭代它。

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

for fname in filenames:
    fhandler = codecs.open(fname, mode="w")

答案 1 :(得分:1)

a_list = [peanut, duck, hair, italy, smile]
for elem in a_list:
    opened_file = codecs.open(elem, mode="w")

答案 2 :(得分:1)

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']
....