[Programmer technical skills] Learning a scripting language python (2) traversing a local file system,

Source: Internet
Author: User

[Programmer technical skills] Learning a scripting language python (2) traversing a local file system,

This article describes how to use python to traverse the local file system and sort files by file size from small to large.

 

In this example, the built-in functions of python and the OS module are used:

  • OS. walk (): This method is used to traverse the specified file directory and returns a three-element tuple (dirpath, dirnames, filenames). Where dirpath is the current directory path and dirnames is the folder under the current path, filenames is the file in the current path.
  • OS. path. join (): Can be used to connect directories and file names, so that you can obtain the full path of a file.
  • OS. path. getsize (): obtains the file size of the specified file.OS. path. join ()If the input is a folder path, return 0L
  • Sorted: iterates an items and returns a new sorted list, which does not affect the original object.

 

With these functions, it is very easy to traverse local files. The first three functions are not described in detail,

The fourth function is described here.SortedUsage:

 

Before talking about sorted, first introduceIterableThe Chinese meaning is the iterator

1. In the Python help documentationIterableThe explanation is:IteralbeIt refers to the object that can return one of its members at a time.

IteralbeThere are three main categories:

The first type is all sequence types, such as list, str, and tuple ). The second type is some non-sequential types, such as dict (dictionary) and file (file ). The third type is any class object that you define that contains the _ iter _ () or _ getitem _ () method.

2. Explanation of the sorted method in python:

Sorted(Iterable [, key] [, reverse])
Function: Return a new sorted list from the items in iterable.

The key and reverse are optional parameters.

 

KeySpecify a comparison function that receives a parameter to extract a keyword for comparison from the buy list element. For example, key = str. lower. The default value is None (direct comparison element)

ReverseIs a Boolean value. If this parameter is set to True, the list elements are sorted in reverse order.

There is also a cmp parameter in the original version, which has been removed now. The compatibility solution isUseFunctools. cmp_to_key ()SetCmp FunctionsConvertKey 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]

The value corresponding to the dictionary is the value in the dictionary key-value pair. d [0] indicates the key.SortedReturns a ancestor list.

Now, all the basic functions are finished. The corresponding code of the example is attached below:

#-*-Coding: UTF-8-*-import osimport OS. pathfilePath = 'd: \ temp 'filelist = [] fileMap = {} size = 0 # traverse files, folders (including subdirectories) in filePath for parent, dirnames, and filenames in OS. walk (filePath): for dirname in dirnames: print ('parent is % s, dirname is % s' % (parent, dirname) for filename in filenames: 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 = lambda d: d [1], reverse = False) for filename, size in B: print ("filename is % s, and size is % d "% (filename, size ))

 

The approximate input is as follows:

Parent is D: \ temp, dirname is 123 parent is D: \ temp, dirname is javaparent is D: \ temp, filename is chydb_14.3_XiaZaiBa.zipthe full name of the file is D: \ temp \ chydb_14.3_XiaZaiBa.zipparent is D: \ temp, filename is DriverGenius_green1.rarthe full name of the file is D: \ temp \ DriverGenius_green1.rarparent is D: \ temp, filename is Firefox39.7zthe full name of the file is D: \ temp \ Firefox39.7z... omitted

 

 

Okay. If you have any questions or file errors, you can leave a message for discussion!

 

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.