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 - Django,用户在应用程序中可以有多个角色,3种类型的用户

python - Pandas 数据框的线性回归

kubernetes - 如何将 kubectl 描述的输出格式化为 JSON

prolog - 强制 prolog 在输出结果中进行替换

python - 从单元测试输出中过滤掉异常消息

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

python - 为什么 python 模块名称有一些大写字母,但总是以小写形式导入?

python - 为什么我要在递归方法上获取和添加行为?

python - 使用 pandas 数据框绘制热图

c++ - 如何在 C++ 中将带有空格的单词分成两列