Python Implements folder traversal

Source: Internet
Author: User

Python in Os.path module for manipulating files or folders

Os.path.exists (path) to determine if the file path exists

dir = "C:\Windows"
If Os.path.exists (dir):
print "DIR exists"
else:
Print "No exists"

Os.path.isfile (path) determines if path is a file

dir = "C:\windows\system32\cmd.exe"
If Os.path.isfile (dir):
Print "File exists"
else:
Print "No exists"

Os.path.getsize (path) Gets the size of the path file

Size = Os.path.getsize (dir)
Print size/1024

Os.path.walk (path) traverses path, returning a ternary group (Dirpath, Dirnames, filenames). Dirpath represents the path that is traversed, Dirnames represents a subdirectory name under that path, is a list, Filesnames represents the file name under that path, and is also a list. For example: When traversing to C:\Windows, Dirpath= "C:\Windows", Dirnames is a list of all the subdirectory names under this path, Dirnames is a list of all the filenames under this path

For (root, dirs, files) in Os.walk ("C:\windows"): Lists all files and filenames under the Windows directory
For filename in Files:
Print Os.path.join (root,filename)

For DIRC in dirs:

Print Os.path.join (ROOT,DIRC)

Question 1 Gets the size of the given folder?

To traverse the size of a file, simply traverse through all the files in the file and add up the size of all the folders

def getdirszie (dir):
for (Root,dirs,files) in Os.walk (Dir,false):
Size = 0
For filename in Files:
Size + = Os.path.getsize (Os.path.join (root,filename))
Print root,size/1024

Question 2 times a subdirectory of a folder, not traversing subdirectories of the word directory?

The Os.listdir (path) function lists the files and folders under the specified directory

dir = ' c:/windows '
If Os.path.exists (dir):
dirs = Os.listdir (dir)
For DIRC in dirs:
Print Dirc
else:
Print "Dir NOT exists"

Python Implements folder traversal

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.