2017-03-02 250 views
0

我想迭代一個目錄並讀取一些文件。 工作目錄設置正確。我打印了dirname和文件名,它應該可以工作。但事實並非如此。Python:「[Errno 2]沒有這樣的文件或目錄」,目錄中有文件

你能幫我嗎?

我的代碼是:

for dirName, subdirList, fileList in os.walk(rootDir): 
    for fname in fileList: 
     if fname.endswith(res): 
      print (dirName) 
      print (fname) 
      with open(fname) as file: 
       for line in file: 
        .... 

而且輸出和錯誤是:

.\86 

output086.csv_cat1.res 

--------------------------------------------------------------------------- 
FileNotFoundError       Traceback (most recent call last) 

<ipython-input-59-9583577f0a41> in <module>() 

    38    print (dirName) 
    39    print (fname) 
    40    with open(fname) as file: 
    41     for line in file: 
    42      x = re.match(regex_x, line) 

FileNotFoundError: [Errno 2] No such file or directory: 'output086.csv_cat1.res' 

問題似乎是40行

+0

只是爲了確認,你試圖訪問的文件被稱爲「output086.csv_cat1.res」而不是「csv_cat1.res」吧? – Chachmu

回答

3

fname只是一個文件名,而不是絕對路徑到您正在嘗試打開的文件。您需要使用目錄的絕對路徑是在加入吧:

import os with open(os.path.join(dirName, fname)) as fh: ...

另外,不要使用file作爲變量名,因爲它是在Python中的內置。