ValueError: invalid literal for int() with base 10; Trying to extract an integer from a float

ValueError: invalid literal for int() with base 10; Trying to extract an integer from a float

我试图让程序识别 NETCDF 文件名中的数字,我更改了代码,但仍然给我同样的错误,我无法确定原因。

产生错误的代码部分是:

Band = int((listofallthefiles[number][listofallthefiles[number].find("M3C" or "M4C" or "M6C")+3:listofallthefiles[number].find("_G16")]))

NETCDF 文件的路径和名称是:

/Volumes/Anthonys_backup/Hurricane_Dorian/August_28/Channel_13/OR_ABI-L2-CMIPF-M6C13_G16_s20192400000200_e20192400009520_c20192400010004.nc

我试图提取 "M6C" 和“_G16”之间的“13”以保存值,但它给我错误消息:

ValueError: invalid literal for int() with base 10: 'olumes/Anthonys_backup/Hurricane_Dorian/August_28/Channel_13/OR_ABI-L2-CMIPF-M6C13'

首先提取你的字符串的数字,以便int可以正确转换它,参见here。 使用 regex 可能更容易,例如:

import re
...
str = listofallthefiles[number]
num = re.findall('.*M6C(.*)_G16', str)[0]

现在您可以将其转换为整数:

val = int(num)