2017-03-02 223 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中的内置。

相关问题