Python:如何使用glob和通配符打开CDF文件

2024-05-15 21:23:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图打开多个.cdf文件并将它们存储在一个命令行中,但是当我尝试在pycdf.CDF()命令中使用通配符时,会返回以下错误:spacepy.pycdf.CDFError: NO_SUCH_CDF: The specified CDF does not exist.

.cdf文件有一个设置的初始名称(instrumentfile)、日期(20010101)和变量部分(可以是1、2、3或4)。这意味着我不能简单地编写如下代码:

DayCDF = pycdf.CDF('/home/location/instrumentfile'+str(dates)+'.cdf')

我还需要更改.cdf数据分配给的变量的名称,因此我正在尝试将数据导入字典(也不确定这是否可行)

当前代码如下所示:

dictDayCDF = {}

for x in range(len(dates)):
    dictDayCDF["DayCDF"+str(x)] = pycdf.CDF('/home/location/instrumentfile'+str(dates[x])+'*.cdf')


并返回错误spacepy.pycdf.CDFError: NO_SUCH_CDF: The specified CDF does not exist.

我也尝试过使用glob.glob,正如我在类似问题的答案中看到的那样,但我还无法解决如何将命令应用于打开.cdf文件:

dictDayCDF = {}

for x in range(len(dates)):
    dictDayCDF["DayCDF"+str(x)] = pycdf.CDF(glob.glob('/home/location/instrumentfile'+str(dates[x])+'*.cdf'))


返回此错误:ValueError: pathname must be string-like

预期的结果是一个.cdf文件的字典,可以用DayCDF1、DayCDF2等名称调用这些文件,无论结束变量节是什么,都可以导入这些文件


Tags: 文件命令名称home错误locationglobdates
1条回答
网友
1楼 · 发布于 2024-05-15 21:23:05

从以下代码框架开始如何:

import glob

for file_name in glob.glob('./*.cdf'):
    print(file_name)
    #do something else with the file_name

至于您遇到的错误消息的根本原因:如果您check the documentation of the method you're trying to use,它表明

Open or create a CDF file by creating an object of this class. Parameters:

pathname : string

name of the file to open or create

基于此,我们可以推断,它期望一个文件名,而不是一个文件名列表。当您试图强制一个文件名列表时,即使用glob的结果,正如您所观察到的,它会抱怨

相关问题 更多 >