Skip to main content
 首页 » 编程设计

python之在python中将列表写入txt文件

2025年05月04日17jillzhang

列表由其中的随机字符串组成

#example 
list = [1,2,3,4] 
 
filename = ('output.txt') 
outfile = open(filename, 'w') 
outfile.writelines(list) 
outfile.close() 

我在文件中的结果

1234 

那么现在我该如何让程序产生我想要的结果:

1 
2 
3 
4 

请您参考如下方法:

myList = [1,2,3,4] 
 
with open('path/to/output', 'w') as outfile: 
  outfile.write('\n'.join(str(i) for i in myList)) 

顺便说一句,您在帖子中的列表包含 int,而不是字符串。
此外,请永远不要将变量命名为 list 或 dict 或任何其他类型