【问题标题】:How to write a table line by line with for loop如何使用for循环逐行编写表格
【发布时间】:2019-04-06 21:25:50
【问题描述】:

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

这是我正在使用的代码的一个小例子:

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)

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

【问题讨论】:

    标签: python arrays export-to-csv


    【解决方案1】:

    您想改用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
    

    【讨论】:

      【解决方案2】:

      您需要遍历要写出的表:

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

      希望有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-11
        • 1970-01-01
        • 2016-03-13
        • 2015-06-04
        • 1970-01-01
        • 2017-01-09
        • 1970-01-01
        相关资源
        最近更新 更多