递归在NetCDF4文件中创建组
在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论