我正在使用for循环来搜索许多目录并提取netcdf文件然后绘制。我查看目录的当前python脚本如下所示:
length = ['05','10','25','50']
time = ['06','12','24','48']
depth = ['100','200','500']
for length in length:
for time in time:
for depth in depth:
nfdir = '/u/gens/nieto/stoch'
ncfn=nfdir + '/stoch_' + length + 'km_' + time + 'h_' + depth + 'm_010T_002S_00U/ncom3d.nc'
我得到的错误是:
IOError: [Errno 2] No such file or directory: '/u/gens/nieto/stoch/stoch_05km_12h_5m_010T_002S_00U/ncom3d.nc'
它将我列表中的500缩短为5,没有目录,因为这不是我正在测试的内容。鉴于这似乎是一个明显的错误,不知道如何解决这个问题。
编辑:只是想注意我对Python比较陌生,所以请原谅代码中的不良品味。
答案 0 :(得分:2)
for depth in depth
,for length in length
..等的for循环导致失败。
改变它们可以解决它。
lengths = ['05','10','25','50'] # <-- renamed length to lengths
times = ['06','12','24','48'] # <-- renamed time to times
depths = ['100','200','500'] # <-- renamed depth to depths
for length in lengths: # <-- use lengths
for time in times: # <-- use times
for depth in depths: # <-- use depths
nfdir = '/u/gens/nieto/stoch'
ncfn=nfdir + '/stoch_' + length + 'km_' + time + 'h_' + depth + 'm_010T_002S_00U/ncom3d.nc'
答案 1 :(得分:1)
为循环变量重用变量名是一个坏主意,因为它会在循环退出后保持不变。请考虑以下示例:
outer_values = ['ab', 'cd', 'ef']
inner_values = ['12', '34', '56']
for outer_values in outer_values:
print('outer: ' + repr(outer_values))
for inner_values in inner_values:
print('inner: ' + repr(inner_values))
# outer: 'ab'
# inner: '12'
# inner: '34'
# inner: '56'
# outer: 'cd'
# inner: '5'
# inner: '6'
# outer: 'ef'
# inner: '6'
在第二次传递时,名称inner_values
仍然绑定到原始inner_values
中迭代的最后一个字符串,即'56'
。在第三次传递中,inner_values
然后只绑定到'6'
。