Python Traversal folder The difference between Listdir walk

Source: Internet
Author: User

一、一级 Directory
' d: \file '; for inch os.listdir (path):p rint (Os.path.join (path,filename)) Use Os.listdir to read all the file names under a directory, and then use Os.path.join to combine the directory path and file name to get the file path, the result is as follows:
D:\file\test1.txt
D:
D:
Case 2: Recursive situation, a directory under the existing directory (directories and files may also have a directory and file) also have files, how to read all the files inside, using Os.walk:

Ii. Directories with sub-directories

Import OS
Path = R ' C:\Users\Administrator\Desktop\file '
For dirpath,dirnames,filenames in Os.walk (path):
Print (Dirpath,dirnames,filenames)
The output results are as follows:

C:\file [' file1 ', ' file2 '] [' file_test1.txt ', ' file_test2. txt ']
C:\file\file1 [] [' file1_test1.txt ', ' file1_test2.txt ']
C:\file\file2 [] [' File2_test1.txt ']

Python Traversal folder The difference between Listdir walk

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.