递归在NetCDF4文件中创建组

发布于 2025-01-18 07:14:13 字数 1228 浏览 3 评论 0原文

在Python中使用 os.makedirs('./folder1/folder2/folder3/',exist_ok=True) 将从父目录“./”创建直到folder3的所有文件夹

我想知道在创建组时是否可以将相同的逻辑应用于netcdf文件。 我制作了这个包装函数,在 Netcdf4 文件中给出 root_grp 将在其中创建一个子组。

def create_group(root_group: netCDF4.Group, group_name: str) -> None:
    """
    create_group
    creates a group inside a netcdf file

    Parameters
    ----------
    root_group : netCDF4.Group
        root group, the new group will be a child of this one
    group_name : str
        name of the child group
    """
    _ = root_group.createGroup(group_name)

我可以通过这种方式创建组。

rootgrp = netCDF4.Dataset(path+"test.nc", "w", format="NETCDF4")
_ = root_group.createGroup(group_name)
create_group(rootgrp,'first')

create_group(rootgrp['first'],'second')

我正在考虑一种递归方式。 是否可以?

我尝试过这种方式

rootgrp = netCDF4.Dataset(path+"test.nc", "w", format="NETCDF4")

path = 'first/second/third'
groups = [grp for grp in path.split('/') if grp != '']
print(groups)
count =0
while count < len(groups):
    current= groups[count]
    rootgrp.createGroup(current)
    print(current)
    rootgrp=rootgrp[current]  
    count+=1

,但它创建了一个组/第一/第二/第三而不是3个嵌套的组。

In python using
os.makedirs('./folder1/folder2/folder3/',exist_ok=True)
will create from the parentdir './' all the folders up to folder3

I wonder if the same logic can be applied to netcdf files when creating groups.
I made this wrapper functions that given a root_grp inside a Netcdf4 file will create a child group inside.

def create_group(root_group: netCDF4.Group, group_name: str) -> None:
    """
    create_group
    creates a group inside a netcdf file

    Parameters
    ----------
    root_group : netCDF4.Group
        root group, the new group will be a child of this one
    group_name : str
        name of the child group
    """
    _ = root_group.createGroup(group_name)

I can the create groups this way.

rootgrp = netCDF4.Dataset(path+"test.nc", "w", format="NETCDF4")
_ = root_group.createGroup(group_name)
create_group(rootgrp,'first')

create_group(rootgrp['first'],'second')

I was thinking of a way to do it recursively.
is it possible?

I tried in this way

rootgrp = netCDF4.Dataset(path+"test.nc", "w", format="NETCDF4")

path = 'first/second/third'
groups = [grp for grp in path.split('/') if grp != '']
print(groups)
count =0
while count < len(groups):
    current= groups[count]
    rootgrp.createGroup(current)
    print(current)
    rootgrp=rootgrp[current]  
    count+=1

But it creates one group /first/second/third instead of 3 nested ones.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文