我有一个二维列表,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/