目录中的python seach文件-无法打开文件



我有文件列表:

import os
import fnmatch
files_template = ['a.txt','b.txt','c.txt','d.txt','e.txt','f.txt']
dir_path = '/users/john'

我需要打开在";files_template";列出并解析其数据,但我可以打开文件

for root, dirs, files in os.walk(dir_path):
for file in files:
if file in files_template:
with open(file, 'r') as fh:
str = fh.read()
print(str)

我收到以下错误消息。

Traceback (most recent call last):
with open(file, 'r') as fh:
FileNotFoundError: [Errno 2] No such file or directory: 'a.txt'

如何修复?

abs_file_path = os.path.join(root, file)
with open(abs_file_path, 'r') as fh:
...

最新更新