0

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

3 回答 3

2

将文件名放入列表并遍历它。

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

for fname in filenames:
    fhandler = codecs.open(fname, mode="w")
于 2013-09-12T06:32:20.107 回答
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']
....
于 2013-09-12T06:34:11.153 回答
1
a_list = [peanut, duck, hair, italy, smile]
for elem in a_list:
    opened_file = codecs.open(elem, mode="w")
于 2013-09-12T06:30:43.733 回答