"Programmer's skill Level" learning a scripting language Python (ii) traverse the local file system

Source: Internet
Author: User
Tags iterable

This article will tell you how to use Python to traverse the local file system, and a small example of how to sort files from small to large by file size

In this example, the main use of Python built-in and the OS module of several functions:

  • This method is used to traverse the specified file directory, returning a ternary tuple (Dirpath, dirnames, filenames), where Dirpath is the current directory path,dirnames is the current path under the folder,filenames is the file under the current path
  • Os.path.join (): can be used to connect directories and file names, so that you can get the full path of a file
  • Os.path.getsize (): Gets the file size of the file, with os.path.join () used, if passed in as a folder path, returns 0L
  • Iterate over an itemsand return a new sorted list without affecting the original object

With these functions, traversing the local file is very simple, the first three functions are not detailed,

Here is the main use of the fourth function sorted :

Before speaking sorted, first introduce iterable , Chinese meaning is an iterator

1. The explanation for iterable in the Python help document is thatIteralbe refers to an object that can return one of its members at once.

Iteralbe mainly consists of 3 categories:

The first class is all sequence types, such as List, str (string), tuple (tuple). The second class is some non-sequential types, such as Dict (dictionary), file (files). The third class is any object that you define that contains the class of the __iter__ () or __getitem__ () method.

2. The sorted method is explained in Python:

Sorted (iterable[, key][, reverse])
Function: Return a newSortedList from the items in iterable.

Where key, and reverse are optional parameters

Key Specifies a comparison function that receives a parameter to extract a keyword from a list element for comparison: for example, Key=str.lower. Default value is None (direct comparison Element)

Reverse is a Boolean value. If set to True, list elements are sorted in reverse order.

There is also a CMP parameter in the original version, which is now removed, and the compatibility scheme is to use functools.cmp_to_key () to convert the CMP function to The key function .

Key returns a lambda, the so-called Lambda is an anonymous small function, lambda d:d[1] corresponds to the code is

def (d):    return d[1]

Corresponds to the dictionary, that is, the value in the Dictionary key-value pair is returned, D[0] represents the key, and the dictionary using sorted Returns a meta-ancestor list

Well, the basic functions are all done, and the corresponding code for the example is attached below:

#-*-coding:utf-8-*-ImportOSImportOs.pathfilepath='D:\temp'fileList=[]filemap={}size=0#traverse files, folders (including subdirectories) under FilePath forParent, Dirnames, filenamesinchOs.walk (filePath): forDirNameinchDirnames:Print('Parent is%s, DirName is%s'%(parent, dirname)) forFileNameinchFilenames:Print('Parent is%s, filename is%s'%(parent, filename))Print('The full name of the file is%s'%os.path.join (parent, filename)) size=Os.path.getsize (os.path.join (parent, filename)) Filemap.setdefault (os.path.join (parent, filename), size)Print("All size is%d"%size) b= Sorted (Filemap.items (), key=LambdaD:D[1], reverse=False) forfilename, sizeinchB:Print("filename is%s, and the size is%d"% (filename, size))

The approximate input is as follows:

Parent is D:\temp, DirName are 123parent is D:\temp, DirName is Javaparent is D:\temp, and filename is Chydb_14.3_xiazaiba. Zipthe full name of the file was D:\temp\chydb_14.3_XiaZaiBa.zipparent is D:\temp, and the filename is drivergenius_green1.rarthe f ull name of the file is D:\temp\DriverGenius_green1.rarparent are D:\temp, filename is firefox39.7zthe full name of the FIL E is D:\temp\Firefox39.7z ... Omitted

Well, if you have any questions or if there is anything wrong with the document, you can leave a message to discuss together!

"Programmer's skill Level" learning a scripting language Python (ii) traverse the local file system

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