输出打印命令并将其附加到 csv 文件

Output and append print command to csv file

我想从 netCDF 文件中读取几个变量并将它们输出到 csv 文件中。

netCDF文件命名如下surfclim_a surfclim_b.

这些文件中包含几个变量。我想在每个文件中提取 2 个名为 MlailMlaih 的变量,并将它们附加到一个 csv 文件中。

为此我做了以下代码:

import netCDF4
from netCDF4 import Dataset
import os
import numpy as np
import csv
stations = ["a", "b"]
inbasedir = "/home/david/test_pals/PALS/sites/"
varname = "surfclim_"
for station in stations:
    os.chdir(inbasedir)
    data = Dataset( varname + station + ".nc")
    lail = (data.variables['Mlail'][:])
    laih = (data.variables['Mlaih'][:])
    a = (station + "_Lail,", lail)
    b = (station + "_Laih,", laih)
    table = a + b
    print (table)
    with open ('LAI.csv', 'w') as ofile:
        writer = csv.writer(ofile)
        [writer.writerow(r) for r in table]

它输出 table 但我没有附加每个站的值,我目前只是覆盖每个结果。

此外,输出文件不是我所期望的:
b,_,L,a,i,l,"," [[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]],[[ 0.0999756]]

有没有人对我有任何提示或解决方案,以便:

1) 您可以简单地使用 'a' 而不是 'w' 打开 csv 文件以追加而不是覆盖。

2) writer.writerow 函数需要一个可迭代对象,因此当 r 是您的站名时,它将字符串视为可迭代的字符。

3) 我无法重现您的括号问题,但也许您可以简单地将数组转换为列表? (有lail = list(lail)

此外,要获得格式正确的 csv 文件,我想您希望 station/variable 名称与值列表位于同一行,不是吗? (假设所有数组具有相同的大小并且是一维的)

终于可以使用writer.writerows()功能了。根据我的建议,您的 for 循环可以变成:

for station in stations:
    os.chdir(inbasedir)
    data = Dataset( varname + station + ".nc")
    lail = data.variables['Mlail'][:]
    laih = data.variables['Mlaih'][:]
    table = [[station + "_Lail", *lail],
             [station + "_Laih", *laih]]
    with open('LAI.csv', 'a') as ofile:
        writer = csv.writer(ofile)
        writer.writerows(table)

这里我使用了 laillaih 的星号解包,这样 table 的每个元素都是一个列表,其中 station/variable 名称中的第一个元素和所有其他元素是价值观。

好处:您可能还想通过将所有内容附加到 table 并在将其写入文件之前将其转置来将它们写在列中。 (恕我直言,这是格式化 csv 文件的更正确方法,仍然假设所有数组都是 1D 且大小相同)。

table = []
for station in stations:
    os.chdir(inbasedir)
    data = Dataset( varname + station + ".nc")
    lail = data.variables['Mlail'][:]
    laih = data.variables['Mlaih'][:]
    table.append([station + "_Lail", *lail])
    table.append([station + "_Laih", *laih])

table_t = list(map(list, zip(*table)))  # Transposes the table
with open('LAI.csv', 'w') as ofile:
    writer = csv.writer(ofile)
    writer.writerows(table_t)