Python learning notes day5-common module learning and python learning notes day5
I. Main Content
Ii. Details
1. Module
A. Definition: the essence is the python file ending with. py. It logically organizes python code to implement certain functions. For example, the file name is test. py --> Module name test.
B. Import method: imort moduname
From mdname import *
From mdname import name as rename
...
C. essence of import (path search and search path)
D. import Optimization: from mdname import test
E. Module classification: modules in the standard library, open-source modules, and custom modules.
2. time & datetime Module
In Python, these methods are usually used to represent the time: 1) timestamp 2) formatted time string 3) there are nine elements in the tuples (struct_time. Since the time module of Python mainly calls the C library, different platforms may be different.
UTC (Coordinated Universal Time) is the Greenwich Mean Time, the world standard Time. UTC + 8 in China. DST (Daylight Saving Time) is the Daylight Saving Time.
Timestamp: Generally, the timestamp indicates the offset calculated in seconds from 00:00:00, January 1, January 1, 1970. We run "type (time. time ()" and return the float type. Functions that return timestamp mainly include time () and clock.
_Time: there are nine elements in struct_time. The main functions that return struct_time include gmtime (), localtime (), and strptime ().
1 # _ * _ coding: UTF-8 _ * _ 2 import time 3 4 5 # print (time. clock () # returns the processor time, which is discarded at the beginning of 3.3 and changed to time. process_time () is used to measure the processing time, excluding sleep time, which is unstable. 6 # print (time) cannot be measured on mac. altzone) # returns the time difference from utc time. \ 7 # print (time. asctime () # return time format "Fri Aug 19 11:14:16 2016", 8 # print (time. localtime () # returns the struct time object format of local time 9 # print (time. gmtime (time. time ()-800000) # returns the struc time object format of utc time 10 11 # print (time. asctime (time. localtime () # return time format "Fri Aug 19 11:14:16 2016", 12 # print (time. ctime () # Return Fri Aug 19 12:38:29 2016 format, same as above 13 14 15 16 # convert the date string into a timestamp 17 # string_2_struct = time. strptime ("2016/05/22", "% Y/% m/% d") # convert a date string to a struct time object in the format of 18 # print (string_2_struct) 19 #20 # struct_2_stamp = time. mktime (string_2_struct) # convert struct time object to timestamp 21 # print (struct_2_stamp) 22 23 24 25 # convert timestamp to string format 26 # print (time. gmtime (time. time ()-86640) # convert the utc timestamp to struct_time format 27 # print (time. strftime ("% Y-% m-% d % H: % M: % S", time. gmtime () # convert the utc struct_time format to the specified string format 28 29 # add or subtract 30 import datetime31 32 # print (datetime. datetime. now () # Return 12:47:03. 94192533 # print (datetime. date. fromtimestamp (time. time () # The timestamp is directly converted to the date format 2016-08-1934 # print (datetime. datetime. now () 35 # print (datetime. datetime. now () + datetime. timedelta (3) # current time + 3 days 36 # print (datetime. datetime. now () + datetime. timedelta (-3) # current time-3 days 37 # print (datetime. datetime. now () + datetime. timedelta (hours = 3) # current time + 3 hours 38 # print (datetime. datetime. now () + datetime. timedelta (minutes = 30) # current time + 30 minutes 39 40 41 #42 # c_time = datetime. datetime. now () 43 # print (c_time.replace (minute = 3, hour = 2) # Replace time
Corresponding format:
1% a local (locale) simplified week name 2% A local full week name 3% B local simplified month name 4% B local full month name 5% c local corresponding date and time represents 6% d the day of the month (01- 31) hour (in 24-hour format, 00-23) in 7% H day 8% I hour (in 12-hour format, 01-12) 9% j the day of the year (001-366) 10% m month (01-12) 11% M minutes (00-59) 12% p local am or pm corresponding to 13% S seconds (01-61) 14% U the number of weeks in a year. (00-53 Sunday is the beginning of a week .) All days before the first Sunday are placed in week 0th. 15% w the day of a week (0-6, 0 is Sunday) 16% W and % U are basically the same, the difference is that % W starts from Monday as a week. 17% x local date 18% X local time 19% y remove century year (00-99) 20% Y complete year 21% Z Time Zone name (if not null characters) 22% %'Format
3. random Module
1 #! /Usr/bin/env python 2 # _ * _ encoding: UTF-8 _ * _ 3 import random 4 print (random. random () #0.6445010863311293 5 # random. random () is used to generate a random number of points from 0 to 1: 0 <= n <1.0 6 print (random. randint (1, 7) #4 7 # random. randint () function prototype: random. randint (a, B) is used to generate an integer in the specified range. 8 # Where parameter a is the lower limit, parameter B is the upper limit, and the generated random number n: a <= n <= B 9 print (random. randrange (510) # random. randrange function prototype: random. randrange ([start], stop [, step]), 11 # obtain a random number from a set in the specified range that increments by the specified base. For example, random. randrange (10,100, 2), 12 # returns a random number from the sequence [10, 12, 14, 16,... 96, 98. 13 # random. randrange (10,100, 2) is equivalent to random. choice (range (10,100, 2) in the result. 14 print (random. choice ('liukuni ') # i15 # random. choice gets a random element from the sequence. 16 # its function prototype is random. choice (sequence ). The sequence parameter indicates an ordered type. 17 # It should be noted that sequence is not a specific type in python, but a series of types. 18 # list, tuple, and string all belong to sequence. For sequence, see the python manual data model chapter. 19 # below are some examples of using choice: 20 print (random. choice ("Learn Python") # Learn 21 print (random. choice (["JGood", "is", "a", "handsome", "boy"]) # List22 print (random. choice ("Tuple", "List", "Dict") # List23 print (random. sample ([1, 2, 3, 3], 3) # [1, 2, 5] 24 # random. the sample function is prototype: random. sample (sequence, k), which randomly obtains a piece of the specified length from the specified sequence. The sample function does not modify the original sequence.View Code
Practical application:
1 #! /Usr/bin/env python 2 # encoding: UTF-8 3 import random 4 import string 5 # random INTEGER: 6 print (random. randint (100) #70 7 8 # randomly select an even number from 0 to: 9 print (random. randrange (0,101, 2) #410 11 # random floating point number: 12 print (random. random () #0.274644556807912913 print (random. uniform (1, 10) #9.88700146319484414 15 # random character: 16 print (random. choice ('abcdefg & # % ^ * F') # f17 18 # select a specific number of characters from multiple characters: 19 print (random. sample ('abcdefghj', 3) # ['F', 'h', 'D'] 20 21 # randomly selected string: 22 print (random. choice (['apple', 'pear ', 'peach', 'Orange ', 'lemon']) # apple23 # shuffling #24 items = [1, 2, 4, 5, 6, 7] 25 print (items) # [1, 2, 3, 4, 5, 6, 7] 26 random. shuffle (items) 27 print (items) # [1, 4, 7, 2, 5, 3, 6]View Code
Randomly generated verification code:
1 # _ * _ coding: UTF-8 _ * _ 2 _ author _ = "ZingP" 3 4 import random 5 security_code = ''6 for I in range ): 7 j = random. randrange (0, 5) 8 if I = j: 9 ptm = random. randint (0, 9) 10 else: 11 ptm = chr (random. randint (97,122) 12 security_code + = str (ptm) 13 print ('security code: ', security_code)View Code
4. OS
Provides an interface for calling the operating system:
1 OS. getcwd () obtains the current working directory, that is, the directory path 2 OS for the current python script. chdir ("dirname") changes the current script working directory, which is equivalent to cd 3 OS in shell. curdir returns the current directory :('. ') 4 OS. pardir: Get the string name of the parent directory of the current directory :('.. ') 5 OS. makedirs ('dirname1/dirname2') can generate multi-layer recursive directory 6 OS. removedirs ('dirname1') if the directory is empty, delete it and recursively go to the upper-level directory. If the directory is empty, delete it, and push 7 OS accordingly. mkdir ('dirname') generates a single-level Directory, which is equivalent to mkdir dirname 8 OS in shell. rmdir ('dirname') deletes a single-stage empty directory. If the directory is not empty, it cannot be deleted. An error is returned, which is equivalent to rmdir dirname 9 OS in shell. listdir ('dirname') List Specify all files and subdirectories in the directory, including hidden files, and print 10 OS in list mode. remove () delete a file 11 OS. rename ("oldname", "newname") rename the file/directory 12 OS. stat ('path/filename ') obtains the file/directory information 13 OS. sep outputs the specific path Separator of the operating system. In win, it is "\", and in Linux it is "/" 14 OS. linesep outputs the line terminator used by the current platform. The line terminator is \ t \ n in win, and the line terminator is \ n in Linux 15 OS. pathsep outputs the string 16 OS used to split the file path. name output string indicates that the current platform is used. Win-> 'nt '; Linux-> 'posix' 17 OS. system ("bash command") runs the shell command and displays 18 OS directly. environ gets the system environment variable 19 OS. path. abspath (path) returns the path normalized absolute path 20 OS. path. split (path) splits the path into two groups of directories and file names and returns 21 OS. path. dirname (path) returns the path directory. In fact, the first element 22 OS. path. basename (path) of OS. path. split (path) returns the final file name of path. If the path ends with a slash (/) or slash (\), a null value is returned. That is, OS. path. the second element of split (path) is 23 OS. path. exists (path) returns True if path exists. If path does not exist, returns False24 OS. path. isabs (path) returns True25 OS if path is an absolute path. path. isfile (path) returns True if path is an existing file. Otherwise, False26 OS. path. isdir (path) is returned. If path is an existing Directory, True is returned. Otherwise, False27 OS is returned. path. join (path1 [, path2 [,...]) after multiple paths are combined, the parameters before the first absolute path are ignored 28 OS. path. getatime (path) returns the last access time of the file or directory pointed to by path 29 OS. path. getmtime (path) returns the last modification time of the file or directory pointed to by path.View Code
5. sys
1 sys. argv command line parameter List. The first element is the program Path 2 sys. exit (n) exit the program. Normally exit (0) 3 sys. obtain the version information of the Python interpreter 4 sys. the maximum Int value of maxint is 5 sys. path returns the search path of the module. during initialization, the value of environment variable PYTHONPATH is 6 sys. platform returns the operating system platform name 7 sys. stdout. write ('Please: ') 8 val = sys. stdin. readline () [:-1]View Code
6. shutilmo Module
Advanced file, folder, and compressed Package Processing Module
Shutil. copyfileobj (fsrc, fdst [, length])
Copy the file content to another file. Partial content is allowed.
View Code
Shutil. copyfile (src, dst)
Copy an object
View Code
Shutil. copymode (src, dst)
Only copy permission. Contents, groups, and users remain unchanged
View Code
Shutil. copystat (src, dst)
Copy status information, including: mode bits, atime, mtime, flags
View Code
Shutil. copy (src, dst)
Copy files and permissions
View Code
Shutil. copy2 (src, dst)
Copy file and status information
View Code
Shutil. ignore_patterns (* patterns)
Shutil. copytree (src, dst, symlinks = False, ignore = None)
Recursively copy objects
Example: copytree (source, destination, ignore = ignore_patterns ('*. pyc', 'tmp *'))
View Code
Shutil. rmtree (path [, ignore_errors [, onerror])
Recursively delete an object
View Code
Shutil. move (src, dst)
Recursively move a file
View Code
Shutil. make_archive (base_name, format ,...)
Create a compressed package and return the file path, such as zip and tar.
- Base_name: the file name of the compressed package. It can also be the path of the compressed package. Only when the file name is used, it is saved to the current directory; otherwise, it is saved to the specified path,
For example, save www => to the current path
For example:/Users/wupeiqi/www => Save to/Users/wupeiqi/
- Format: Compressed package type, "zip", "tar", "bztar", and "gztar"
- Root_dir: Path of the folder to be compressed (default current directory)
- Owner: user. The current user is used by default.
- Group: group. Default Value: current group.
- Logger: used to record logs, usually a logging. Logger object.
More: http://www.cnblogs.com/wupeiqi/articles/4963027.html
7. json & pickle Module
Two modules used for serialization
Json, used for conversion between string and python Data Types
Pickle, used for conversion between python-specific types and python Data Types
The Json module provides four functions: dumps, dump, loads, and load.
The pickle module provides four functions: dumps, dump, loads, and load.
1 import pickle 2 a = {'A': 'bc', 'C': 'hello', 'D': 123, 'E ': 'World'} 3 f = open ('a. pkl ', 'wb') 4 pickle. dump (a, f) # If the cross-language platform uses json 5 f. close () 6 ''' 7 >>> a = {'A': 'bc', 'C': 'hello', 'D': 123, 'E ': 'World'} 8 >>> import json 9 >>> json. dumps (a) 10 '{"a": "bc", "d": 123, "e": "world", "c ": "hello"} '11 >>> B = json. dumps (a) 12 >>> json. loads (B) 13 {'A': 'bc', 'D': 123, 'E': 'World', 'C': 'hello'} 14 '''View Code1 import pickle2 f = open ('A. pkl', 'rb') 3 acc = pickle. load (f) 4 print (acc)View Code
8. shelve
The shelve module is a simple k. v uses the memory data through the file persistence module to persist any python data formats supported by pickle.
1 import shelve 2 3 d = shelve. open ('shelve _ test') # open a file 4 5 class test (object): 6 def _ init _ (self, n): 7 self. n = n 8 9 10 t = Test (123) 11 t2 = Test (123334) 12 13 name = ["alex", "rain ", "test"] 14 d ["test"] = name # persistence list 15 d ["t1"] = t # persistence Class 16 d ["t2"] = t217 18 d. close ()View Code
9. xml Processing
10. yaml Processing
11. configparser
12. hashlib
13. subprocess
14. logging Module
15. re Regular Expression
16. glob Module