Python二维列表: exporting as delimited text file

标签 python multidimensional-array

我有一个二维列表,myList[r][c],其中有 r 行,每行 c 列。

我正在尝试将它导出到一个文本文件中,每个列元素由竖线分隔 | , 以及每行末尾的 & 符号。

myList = [[[] for a in range(c)] for b in range(r)]

{a bunch of code populating  myList}

f = open("myfile.txt","w")
for x in range(0,r):
    thisRow = ''
     for y in range(0,c):
          appendThis = myList[x][y]
          thisRow += appendThis + "|"
     f.write(thisRow)
     f.write("&")
f.close

...但是我在添加竖线字符的行上得到 TypeError: can only concatenate list (not "str") to list

最佳答案

csv 模块就是为此而制作的。 Python 2.7 示例:

import csv
r=7
c=5
myList = [[b*10+a for a in range(c)] for b in range(r)]

with open("myfile.txt","wb") as f:
    w = csv.writer(f,delimiter='|',lineterminator='&\r\n')
    w.writerows(myList)

输出:

0|1|2|3|4&
10|11|12|13|14&
20|21|22|23|24&
30|31|32|33|34&
40|41|42|43|44&
50|51|52|53|54&
60|61|62|63|64&

关于Python二维列表: exporting as delimited text file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41405347/

相关文章:

PHP SoapClient : How to pass complex-type parameters to a webservice?

Java 2D 数组问题

python - 为什么拆包会以元组形式给出结果

python - Python、Pandas 和 Excel 的列问题;;

python - 使用 Python 下载文件

Python - Pandas - 将特定函数应用于给定级别 - 多索引数据帧

javascript - 如何展平夹紧的阵列

c - 多维数组的值为 "skipped"的奇怪错误

javascript - 你会如何在 javascript 中编写一个遍历数组数组的算法?

Python在目录中创建不需要的文件夹