我有不同的文件,我在其中選取了一些數(shù)據(jù)/值,以便生成一個(gè)對(duì)所有內(nèi)容進(jìn)行分組的表格。這是我正在使用的代碼的一個(gè)小例子: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)但是這段代碼只將所有站的所有結(jié)果寫在一行中。為了讓每個(gè)站的代碼在下一行寫入數(shù)據(jù)/值,我需要更改什么?
2 回答

qq_遁去的一_1
TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
你想writer.writerows(table_t)改用。
writerows() 方法進(jìn)行迭代并為列表中的每個(gè)項(xiàng)目創(chuàng)建行。
例子:
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
添加回答
舉報(bào)
0/150
提交
取消