Python 巨蟒:“;[Errno 2]没有这样的文件或目录";文件在目录中

Python 巨蟒:“;[Errno 2]没有这样的文件或目录";文件在目录中,python,operating-system,Python,Operating System,我想遍历一个目录并读取一些文件。 工作目录设置正确。我打印了文件名和文件名,应该可以用了。但事实并非如此 你能帮帮我吗 我的代码是: for dirName, subdirList, fileList in os.walk(rootDir): for fname in fileList: if fname.endswith(res): print (dirName) print (fname) wit

我想遍历一个目录并读取一些文件。 工作目录设置正确。我打印了文件名和文件名,应该可以用了。但事实并非如此

你能帮帮我吗

我的代码是:

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'
\86
output086.csv_cat1.res
---------------------------------------------------------------------------
FileNotFoundError回溯(最近一次调用上次)
在<模块>()
38印刷品(名称)
39印刷品(fname)
40打开(fname)作为文件:
41对于文件中的行:
42 x=重新匹配(正则表达式x,行)
FileNotFoundError:[Errno 2]没有这样的文件或目录:“output086.csv\u cat1.res”

问题似乎出在第40行。

fname
只是一个文件名,而不是您试图打开的文件的绝对路径。您需要将其与所在目录的绝对路径联接:

导入操作系统
将open(os.path.join(dirName,fname))作为fh:
...


另外,不要将
file
用作变量名,因为它是python中内置的。

fname
只是一个文件名,而不是您试图打开的文件的绝对路径。您需要将其与所在目录的绝对路径联接:

导入操作系统
将open(os.path.join(dirName,fname))作为fh:
...


另外,不要使用
文件作为变量名,因为它是python中内置的。

请确认,您尝试访问的文件名为“output086.csv\u cat1.res”,而不是“csv\u cat1.res”,对吗?请确认,您尝试访问的文件名为“output086.csv\u cat1.res”,而不是“csv\u cat1.res”,对吗?