python - 用空格分隔的写入行将列表列表写入文本文件?

标签 python output-formatting

我想使用 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]))

关于python - 用空格分隔的写入行将列表列表写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53700090/

相关文章:

python - 在 pymongo 的 MongoClient() 中包含一个 key 文件

python - 输出格式 Python 3.3

bash - 在 bash 中,我如何添加带前导零的整数并维护指定的缓冲区

python - 导入 Pandas 时导致大量内存提交的原因

python - 如何在 Pandas 中选择不同大小的代码?

python - Facebook 营销 API - Python 获取洞察力 - 达到用户请求限制

python - 如何打印 Tkinter Text 小部件的内容?

r - 覆盖 dplyr 中的 "Variables not shown",以显示来自 df 的所有列

python - 如何将嵌套字典的内容写入特定格式的文件?