How Python gets all the files in the directory

Source: Internet
Author: User
This example describes how Python obtains all the files in the directory. Share to everyone for your reference. The specific analysis is as follows:

Os.walk ()

function declaration: Walk (Top,topdown=true,onerror=none)

1. The parameter top indicates the path of the directory tree to traverse

2. The default value of the parameter topdown is "True", which means that the files under the directory tree are returned first, and then the subdirectories of the directory tree are traversed. When the value of Topdown is "False", it means traversing a subdirectory of the directory tree, returning the file under the subdirectory, and finally returning the file under the root directory

3. The default value of the parameter onerror is "None", which means that errors resulting from file traversal are ignored. If not NULL, provide a custom function tip error message after continuing to traverse or throw an exception to abort the traversal

4. The function returns a tuple that has 3 elements, each of which represents the path name of each traversal, the directory list, and the file list

def getlistfiles (path):   assert Os.path.isdir (path), '%s not exist. '% path   ret = []   for Root, dirs, files in O S.walk (path):     print '%s,%s,%s '% (root, dirs, files) for     filespath in Files:       ret.append (Os.path.join (Root, Filespath))   return ret  print len (getlistfiles ('. '))

Hopefully this article will help you with Python programming.

  • Related Article

    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: 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.