我有不同的文件,在这些文件中,我提取一些数据/值以产生将所有内容分组的表。
这是我正在使用的代码的一个小示例:
stations = ["AAA", "BBB", "CCCC", "DDDD"]
datadir = "/home/data/"
table = []
for station in stations:
os.chdir(datadir)
nc = Dataset(station + ".nc", 'r+')
p = (nc.variables['Rainf'][:,0,0]
evap = nc.variables['Qle'][:,0,0]
table.append(p)
table.append(evap)
table_t=list(table)
with open (datadir + "table.csv", 'w') as ofile:
writer = csv.writer(ofile)
writer.writerow(table_t)
但是此代码仅将所有工作站的所有结果写入一行。为了使每个站代码将数据/值写到下一行,我需要更改什么?
答案 0 :(得分:2)
您想改用writer.writerows(table_t)
。
writerows()
方法进行迭代,并为列表中的每个项目创建行。
示例:
data = [list(i) for i in 'abcde fhghi jklmn opqrs'.split()]
# [['a', 'b', 'c', 'd', 'e'],
# ['f', 'h', 'g', 'h', 'i'],
# ['j', 'k', 'l', 'm', 'n'],
# ['o', 'p', 'q', 'r', 's']]
with open('test.csv','w') as file:
writer = csv.writer(file, lineterminator='\n')
writer.writerows(data)
# test.csv
# a,b,c,d,e
# f,h,g,h,i
# j,k,l,m,n
# o,p,q,r,s
答案 1 :(得分:1)
您需要遍历要写出的表:
with open (datadir + "table.csv", 'w') as ofile:
writer = csv.writer(ofile)
for row in table:
writer.writerow(row)
希望有帮助。