Method One: Using the function
os.walk()
os.walk()
will return ternary tuples(dirpath, dirnames, filenames)
dirpath
: Root Path (String)
dirnames
: All directory names under path (list)
filenames
: All non-directory file names under path (list)
The directory name and file name are not added to the root path, so a full path is required to connect the directory name or file name to the root path.
Example:
import osroot = "C:\\dir"for dirpath, dirnames, filenames in os.walk(root): for filepath in filenames: print os.path.join(dirpath, filepath)
Method Two: Using the function os.listdir()
, os.path.isdir()
os.path.isfile()
os.listdir()
You can list all file and directory names under the path, but do not include the current directory .
, the parent directory, ..
and the files under subdirectories.
os.path.isfile()
And os.path.isdir()
determine if the current path is a file or directory
Example:
import osdef listDir(rootDir): for filename in os.listdir(rootDir): pathname = os.path.join(rootDir, filename) if (os.path.isfile(filename)): print pathname else: listDir(pathname)
Python Traversal folder