假设我的文件结构:
First_Folder
|____Second_Folder
|___file1.txt
|____Third_Folder
|___file2.txt
使用os.walk()
for r, d, f in os.walk ('First_Folder'):
if f:
print ('File found!')
else:
print ('File not found.')
输出:
File not found.
File found!
File found!
如何告诉os.walk()仅查找子目录中的文件Second_Folder和Third_Folder?正确的结果应该是:
File found!
File found!
答案 0 :(得分:1)
我认为os.walk
可以选择这样做,但您可以自行检查:
for r, d, f in os.walk ('First_Folder'):
# We only want subdirectories.
if r == 'First_Folder':
continue
if f:
print ('File found!')
else:
print ('File not found.')
或者,如果您只查找具有特定模式的文件(例如所有.txt文件),则可以使用glob:
import glob
# matches *.txt files in subdirectories of "First_Folder"
files = glob.glob('First_Folder/*/*.txt')