我是Python新手。我正在尝试在CSV文件中写入数字。第一个数字构成行的第一个元素。第二个数字,然后一个新行应该开始。但是,我的代码的工作方式,而不是将第二个元素添加到同一行,它创建一个新行。
例如我想要的是:
a1,b1
a2,b2
但我得到的是:
a1
b1
a2
b2
我使用循环连续将值写入CSV文件:
n = Ratio # calculated in each loop
with open('ex1.csv', 'ab') as f:
writer = csv.writer(f)
writer.writerow([n])
...
m = Ratio2 # calculated in each loop
with open('ex1.csv', 'ab') as f:
writer = csv.writer(f)
writer.writerow([m])
我希望结果的格式为
n1,m1
n2,m2
答案 0 :(得分:1)
写入文件然后将其读回并打印的示例:
import csv
with open('ex1.csv', 'w') as f: # open file BEFORE you loop
writer = csv.writer(f) # declare your writer on the file
for rows in range(0,4): # do one loop per row
myRow = [] # remember all column values, clear list here
for colVal in range(0,10): # compute 10 columns
m = colVal * rows # heavy computing (your m or n)
myRow.append(m) # store column in row-list
writer.writerow(myRow) # write list containing all columns
with open('ex1.csv', 'r') as r: #read it back in
print(r.readlines()) # and print it
输出:
['0,0,0,0,0,0,0,0,0,0\r\n', '0,1,2,3,4,5,6,7,8,9\r\n', '0,2,4,6,8,10,12,14,16,18\r\n', '0,3,6,9,12,15,18,21,24,27\r\n']
转换为
文件0,0,0,0,0,0,0,0,0,0
0,1,2,3,4,5,6,7,8,9
0,2,4,6,8,10,12,14,16,18
0,3,6,9,12,15,18,21,24,27
您还可以将每个行列表(通过myList[:]
复制)填充到另一个列表中,并使用writer.writerows([ [1,2,3,4],[4,5,6,7] ])
一次性写入所有行。
请参阅:https://docs.python.org/2/library/csv.html#writer-objects或https://docs.python.org/3/library/csv.html#writer-objects