如何使用for循环逐行写入表格



我在不同的文件中获取一些数据/值,以便生成一个对所有内容进行分组的表。

下面是我使用的代码的一个小例子:

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)

但这段代码只将所有站点的所有结果写在一行中。为了让每个工作站的代码将数据/值写入下一行,我需要更改什么?

您需要使用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

您需要迭代要写出的表:

with open (datadir + "table.csv", 'w') as ofile:
writer = csv.writer(ofile)
for row in table:
writer.writerow(row)

希望能有所帮助。

最新更新