Python Traversal folder

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.