将列表列表写入文件,每个元素使用一个新行

时间:2014-01-23 02:42:38

标签: python

    file = open("myfile.txt","w")
    aList = [["Hello","1","2"],["Hello","3","4"],["Hello","5","6"]]

    for element in aList:
        file.writelines("\n".join(element))

它出现在文本文件中的方式:

Hello
1
2Hello
3
4Hello
5
6

我希望它能在文本文件中出现:

Hello
1
2
Hello
3
4
Hello
5
6

我在for循环中做错了什么,我该如何解决?

2 个答案:

答案 0 :(得分:2)

import itertools
aList = [["Hello","1","2"],["Hello","3","4"],["Hello","5","6"]]
with open('myfile.txt', 'w') as outfile:
    for e in itertools.chain.from_iterable(aList):
        outfile.write(e+'\n')

答案 1 :(得分:1)

只需在每element之后添加一个新行:

for element in aList:
    file.writelines("\n".join(element))
    file.write("\n")