2

我想用 , 将列表列表写入文本文件writelines(),并使用空格作为分隔符。有没有比下面的代码更简单的方法?

myList = [[1, 'A1', 100, '1001', '1', '1001', 'aa'],
          [2, 'B1', 101, '3008', '2', '3008', 'bb'],
          [3, 'C1', 102, '6987414', '3', '6987414', 'cc']]
strList = []
for row in myList:
    myList = [str(item) for item in row]
    strList.append(myList)

with open(r"D:/20181210", "w",encoding="utf-8") as fo:
    for row in strList:
        list1 = [(item+" ") for item in row  ]
        fo.writelines( list1)
        fo.write('\n')

然后我的文本文件输出如下所示:

1 A1 100 1001 1 1001 aa 
2 B1 101 3008 2 3008 bb 
3 C1 102 6987414 3 6987414 cc 

结果是对的,但我认为我的代码不是最简单的。

4

2 回答 2

3

或使用write并使用嵌套str.join

with open(r"D:/20181210", "w",encoding="utf-8") as fo:
    fo.write('\n'.join([' '.join(i) for i in myList]))
于 2018-12-10T05:48:31.193 回答
0

要么按照 Barmar 的建议使用 stdlibcsv模块,要么使用 genexp 构建字符串str.join

lines = [['some', 'space', 'separated', 'fields'],
         ['in', 'a', 'few', 'rows']]

with open(filename, 'w') as fout:
    fout.writelines(' '.join(line) for line in lines)
于 2018-12-10T05:46:18.323 回答