Reading all files in all directories [duplicate] Reading all files in all directories [duplicate] python python

Reading all files in all directories [duplicate]


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 globfor 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 osimport fnmatchfor 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.