如何添加多个编解码器.打开到“for”循环

2024-04-18 22:36:46 发布

您现在位置: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()

Tags: 模块txtforstylemodeopencodecsduck
3条回答
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']
....

将文件名放入一个列表中并遍历它。你知道吗

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")

相关问题 更多 >