列表由其中的RANDOM字符串组成

#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,而不是字符串。
另外,请勿为此变量命名listdict或任何其他类型的变量

关于python - 在python中将列表写入txt文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20334893/

10-11 21:29