Python: Reading all files in all directories
This question already has an answer here:
Python doesn't support wildcards directly in filenames to the open()
call. You'll need to use the glob
module instead to load files from a single level of subdirectories, or use os.walk()
to walk an arbitrary directory structure.
Opening all text files in all subdirectories, one level deep:
import glob
for filename in glob.iglob(os.path.join('Test', '*', '*.txt')):
with open(filename) as f:
# one file open, handle it, next loop will present you with a new file.
Opening all text files in an arbitrary nesting of directories:
import os
import fnmatch
for dirpath, dirs, files in os.walk('Test'):
for filename in fnmatch.filter(files, '*.txt'):
with open(os.path.join(dirpath, filename)):
# one file open, handle it, next loop will present you with a new file.
链接地址: http://www.djcxy.com/p/20040.html
下一篇: Python:读取所有目录中的所有文件