我想用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
结果是正确的,但我认为我的代码不是最简单的。
或者使用write
并使用嵌套的str.join
:
with open(r"D:/20181210", "w",encoding="utf-8") as fo:
fo.write('n'.join([' '.join(i) for i in myList]))
按照Barmar的建议使用stdlibcsv
模块,或者使用str.join
和genexp构建字符串。
lines = [['some', 'space', 'separated', 'fields'],
['in', 'a', 'few', 'rows']]
with open(filename, 'w') as fout:
fout.writelines(' '.join(line) for line in lines)