2016-09-20 72 views
0

我想通過一系列.nc文件來運行一小段代碼。下面的測試腳本打印在目錄中的第一個文件名,但是當我使用ncfile = netCDF4.Dataset(fname, 'r')我得到的錯誤Python os.walk netCDF4不能一起工作

File "netCDF4\_netCDF4.pyx", 
line 1795, in netCDF4._netCDF4.Dataset.__init__ 
(netCDF4\_netCDF4.c:12278) 
    RuntimeError: No such file or directory 

這是一個不兼容的問題與os.walk和netCDF4或者是一個簡單的錯誤,我在做什麼?

import os 
import netCDF4 

for root, dirs, files in os.walk('E:\satellite .nc data\ENVISAT2006'): 
    for fname in files: 
     print fname # works up to here and without line below it prints all filenames 
     ncfile = netCDF4.Dataset(fname, 'r') 

回答

1

現在看來,這是需要在

ncfile = netCDF4.Dataset(fname, 'r')

的路徑和目錄的一個簡單的問題,所以我有

ncfile = netCDF4.Dataset(os.path.join(fdir,fname), 'r')

取代它和外部的指定fdir循環。爲了簡單起見,我用os.listdir替換了os.walk,因爲我不需要通過目錄樹。

import os 
import netCDF4 
import numpy as np 
from math import pi 
from numpy import cos, sin 

fdir = 'E:\satellite .nc data\ENVISAT2006' 
for fname in os.listdir('E:\satellite .nc data\ENVISAT2006'): 
#os.walk only needed if going through all of the files in a directory tree 
    #for fname in files: 
    print fname 
    ncfile = netCDF4.Dataset(os.path.join(fdir,fname), 'r')