Skip to main content
 首页 » 编程设计

python之对于列表的每个成员,将其写入单独的文件 python

2025年05月04日9linjiqin

我有一个长度为 n 的列表。列表的每一项都需要写入 n 个 .txt 文件。由于某种原因,以下基本方法对我不起作用:

for item in lst: 
     for i in range(len(lst)): 
         write_to_me = open('list_item_%i.txt' %i, 'w')  
         write_to_me.write(item) 

文件名没问题(“list_item_0.txt”、“list_item_1.txt”等),但每个文件都写入了相同的项目。所以我最终得到了 n 个文件,每个文件中都有重复的内容。有什么想法吗?

请您参考如下方法:

不要使用嵌套循环。使用 enumerate获取索引和项目:

 for i, item in enumerate(lst): 
     write_to_me = open('list_item_{0}.txt'.format(i), 'w')  
     write_to_me.write(item) 
     write_to_me.close() 

旁注:使用完后不要忘记关闭文件!