我想从目录结构如下的特定文件中读取数据:
-Directory
-Subdirectory1
-AGreek.srt
-AEnglish.srt
-Subdirectory2
-BGreek.srt
-BEnglish.srt
-test.py
其中test.py是我的脚本,应该只读取Directory
中的英文文件。这是我当前的脚本:
import os
substring = 'English.srt'
for root, subdirs, files in os.walk('Directory'):
for filename in files:
if substring in filename:
fp = open(os.path.abspath(filename))
# Further Action
但是这给了我以下错误:
FileNotFoundError: [Errno 2] No such file or directory: '/home/coder/Spam/AEnglish.srt'
如何解决该错误? (P.s .: Spam
是Directory
和test.py
所在的文件夹)
答案 0 :(得分:0)
您需要使用os.path.join(root,filename)
来访问文件。
例如:
import os
substring = 'English.srt'
for root, subdirs, files in os.walk('Directory'):
for filename in files:
if substring in filename:
fp = open(os.path.join(root,filename))
# Further Action