Python common modules

Source: Internet
Author: User

Common modules

Http://www.cnblogs.com/alex3714/articles/5161349.html


######### #模块 ############

Import Call Module

Call a function of a module separately
From time Import Sleep # #调用time模块的sleep函数 (can be used, take more than one)
Sleep (1)
Print (' Afsasdas ')

# # #改变模块内的函数名字
From time import sleep as Stop # #将sleep改成stop
Stop (1)
Print (' Afsasdas ')

# #获取文件的路径
Print (__file__) # #结果C:/users/administrator/pycharmprojects/untitled3/test/import mode call
# # #获取文件目录的绝对路径 (from a layer of relative paths)
Print (Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)))
# #结果
C:\Users\Administrator\PycharmProjects\untitled3

# # #__name__变量在当前文件中为__main__在其他文件中调用就为所调用文件的文件名
Print (__name__) # #结果__main__

Time Module (Times)


1.sleep #睡眠时间 time.sleep (1)
2.strftime # #类似shell中的date命令
time_format= '%y-%m-%d%x '
Print (Time.strftime (Time_format))
Results 2017-12-21 17:53:35
**********
You can use print like this (Time.strftime ('%y--%m--%d%x ', Time.localtime ()))
Results 2017--12--25 21:23:05

3.time #计算时间 (computer birth to Present time 1970) in seconds
Print (Time.time ()) #结果 1514207184.7077286
4.localtime # #当前时间 (structured display) print (Time.localtime ())
Showing results time.struct_time (tm_year=2017, tm_mon=12, tm_mday=25, tm_hour=21, tm_min=13, tm_sec=7, tm_wday=0, tm_yday=359, tm_ isdst=0)
5.strptime # #转换为格式化时间显示 Print (Time.strptime (' 2017--12--25 21:23:05 ', '%y--%m--%d%x '))
#结果 time.struct_time (tm_year=2017, tm_mon=12, tm_mday=25, tm_hour=21, tm_min=23, tm_sec=5, tm_wday=0, tm_yday=359, tm_ ISDST=-1)
6.ctime #显示当前时间 Print (Time.ctime ()) #结果 Mon Dec 25 21:35:00 2017
7.mktime #以秒的格式显示当前时间 Print (Time.mktime (Time.localtime ()))
Results # 1514209097.0


Print (Time.time ()) #1514209097.3601263
Print (Time.mktime (Time.localtime ())) #1514209097.0

# # # #datetime模块 (Time)
1.datetime.now # #显示时间 Print (Datetime.datetime.now ())
#结果 2017-12-25 21:41:53.292476


Random (stochastic number module)


1.randint # #生成自定义的随机数 (including mantissa) print (Random.randint (1,10)) #生成1-10 random number
2.random #生成大于0小于1的16位的随机数 Print (Random.random ()) #结果 0.9182025488823987
3.choice #在一个序列中随机打印一个内容 Print (Random.choice ([' Q ', ' W ', ' e ')) or print (Random.choice (' Hello '))
4.sample #在一个序列中随机选择n个内容print (Random.sample ([1,3,6,7],2))
#结果 [3, 1]
5.randrange #自定义范围选择随机数 (Gu Tou regardless of tail) print (Random.randrange (1,3)) # #1到2的随机数 (excluding 3)


OS (operating system module)


1.GETCWD # #获取当前文件的工作目录 (catalog) print (OS.GETCWD ()) # #结果C: \users\administrator\pycharmprojects\untitled3\test
2.chdir # #改变当前文件或脚本的工作目录
Print (OS.GETCWD ())
Os.chdir (R ' C:\Users ') # # #改变工作目录
Print (OS.GETCWD ())
Results
C:\Users\Administrator\PycharmProjects\untitled3\test
C:\Users
3.curdir # #返回当前目录 like a CD.
Print (OS.GETCWD ())
Print (Os.curdir)
Results
C:\Users
. #点
4.pardir # #返回上一级目录 like CD. Print (Os.pardir) # #结果: (2 points)
5.makedirs # #创建多个目录 (default current directory) Os.makedirs (' A\\bb ')
6.removedirs # #删除多个空目录 (non-empty not deleted) os.removedirs (' A\\bb ')
7.mkdir # #创建一个目录 Os.mkdir (' AAAA ')
8.rmdir # #删除一个目录 Os.rmdir (' AAAA ')
9.listdir # #把某个目录下的所有文件及目录以一个list的格式显示os. Listdir (R ' \users\administrator\pycharmprojects\untitled3 ')
10.remove # #删除一个文件 (file only) Os.remove (' V ')
11.rename # #改文件或目录的名字 Os.rename (' v1 ', ' vvv1 ')
12.stat # #显示文件或目录的详细信息 (Shell-like stat) print (Os.stat (R ' aa\b\qqq.py ')) (can see file size)
#结果
Os.stat_result (st_mode=33206, st_ino=2533274790532240, st_dev=701016, St_nlink=1, St_uid=0, St_gid=0, st_size=0, St_ atime=1514293889, st_mtime=1514293889, st_ctime=1514293889)
13.SEP # #获取当前操作系统路径分割符 linux=/win=\ print (OS.SEP)
14.LINESEP # #换行分隔符 win=\r\n linux=\n mac=\r
15.PATHSEP # #输出分割文件路径路径的分隔符 Print (OS.PATHSEP)
16.name #输出字符串指定当前使用平台 win=nt linux=posix print (os.name)
17.system # #运行shell命令 Print (Os.system (' ping baidu.com '))
18.environ # #获取系统环境变量 (dictionary form) print (Os.environ)
19.path.abspath # #获取文件或目录的绝对路径 Print (Os.path.abspath (' AA '))
20.path.split# #以元祖形式将文件分成 (path and file name) based on the last slash
Print (Os.path.split (R ' C:\Users\Administrator\PycharmProjects\untitled3\test\aa '))
Results
(' c:\\users\\administrator\\pycharmprojects\\untitled3\\test ', ' AA ')
Absolute path to the 21.path.dirname #获得目录或文件的母目录 (previous directory)
Print (Os.path.dirname (R ' C:\Users\Administrator\PycharmProjects\untitled3\test '))
Results
C:\Users\Administrator\PycharmProjects\untitled3
22.path.basename #获取目录或文件 (delimiter last file or directory)
Print (Os.path.basename (R ' C:\Users\Administrator\PycharmProjects\untitled3\test '))
Results
Test
23.path.exists # #判断文件存不存在 (existence true does not exist false) print (Os.path.exists (R ' C:\Users\Administrator\PycharmProjects\ Untitled3\test '))
24.path.isabs # #判断是否为绝对路径 (is return true not return false) print (Os.path.isabs (' Test '))
25.path.isfile # #判断是否为文件print (os.path.isfile (' B '))
26.path.isdir #判断是否为目录 Print (Os.path.isdir ('.. /test '))
27.path.join # #路径拼接 Print (Os.path.join (R ' C:\Users\Administrator ', ' B '))
Results
C:\Users\Administrator\b
28.path.getatime # #获取文件的最后存取时间 Print (Os.path.getatime (R ' C:\Users\Administrator '))
Results
1513490467.9614303
29.path.getmtime #获取文件的最后修改时间print (Os.path.getmtime (R ' C:\Users\Administrator '))
Results
1513490467.9614303

SYS (Python interpreter module)


1.ARGV # #以列表的形式进行传参 (the first is the absolute path and file name)
2.exit # #退出程序exit (0) for normal
3.path # #搜寻模块路径 (displayed as a list) print (Sys.path)
4.platform # #返回操作系统名称 Print (sys.platform)


Hashlib (Encryption module)


1.MD5 # #加密
A=HASHLIB.MD5 ("Hello". Encode (' UTF8 ')) # #加密hello (character encoding required)
Print (A.hexdigest ()) # #hexdigest (returned in 16 binary) #结果5d41402abc4b2a76b9719d911017c592
2.sha (1-512) # #1到512都是加密算法 commonly used sha3_256 decryption display is also used Hexdigest


Logging (log module)

Http://www.cnblogs.com/yuanchenqi/articles/5732581.html

By default, Python's logging module prints the logs to standard output and only displays logs that are greater than or equal to the warning level, indicating that the default logging level is set to warning (log level level critical > ERROR > WARNING > INFO > DEBUG > NOTSET), the default log format is log level: Logger name: User output message.

First, simple to use
Import logging
Logging.debug (' Debug message ')
Logging.info (' info message ')
Logging.warning (' warning message ') # #打印
Logging.error (' error message ') # #打印
Logging.critical (' critical message ') # #打印

Two flexible configuration log level, log format, output location
Import logging
Logging.basicconfig (level=logging. DEBUG,
format= '% (asctime) s% (filename) s[line:% (lineno) d]% (levelname) s% (message) s ',
Datefmt= '%a,%d%b%Y%h:%m:%s ',
Filename= '/tmp/test.log ',
Filemode= ' W ')

Logging.debug (' Debug message ')
Logging.info (' info message ')
Logging.warning (' warning message ')
Logging.error (' Error message ')
Logging.critical (' critical message ')


FileName: Creates a filedhandler with the specified file name (the concept of handler is explained in the back) so that the log is stored in the specified file.
FileMode: File is opened by using this parameter when filename is specified, and the default value is "a" and can be specified as "W".
Format: Specifies the log display format used by handler.
DATEFMT: Specifies the date time format.
Level: Set the log levels for Rootlogger (which will explain the concepts behind)
Stream: Creates a streamhandler with the specified stream. You can specify the output to Sys.stderr,sys.stdout or the file (F=open (' Test.log ', ' W ')), and the default is Sys.stderr. If you list both the filename and stream two parameters, the stream parameter is ignored.

##########
formatting strings that may be used in the format parameter:
% (name) s logger name
% (Levelno) s log level in digital form
% (levelname) s log level in text form
% (pathname) s calls the full pathname of the module of the log output function and may not have
% (filename) s The file name of the module that called the log output function
% (module) s call the module name of the log output function
% (FuncName) s Call the function name of the log output function
% (Lineno) d The line of code where the statement of the log output function is called
% (created) F current time, represented by the UNIX standard floating-point number representing the time
% (relativecreated) d when the log information is output, the number of milliseconds since logger was created
% (asctime) s The current time in string form. The default format is "2003-07-08 16:49:45,896". The comma is followed by milliseconds
% (thread) d thread ID. Probably not.
% (threadname) s thread name. Probably not.
% (process) d process ID. Probably not.
% (message) s user-output message


Configparser (configuration file module)

Http://www.cnblogs.com/alex3714/articles/5161349.html

1.ConfigParser

Import Configparser
Config=configparser. Configparser ()
config["DEBUG"]={
' Name ': ' Zhangbin ',
' Age ': ' 23 ',
' Max ': ' Male '
}
With open (' Example.ini ', ' W ') as ConfigFile:
Config.write (ConfigFile)

# #结果
[DEBUG]
Name = Zhangbin
Age = 23
max = Male

# # # # #对配置文件的操作 http://www.cnblogs.com/alex3714/articles/5161349.html

First, read

1.sections # #以list查看所有块 Print (Config.sections ())
2.defaults # #以list查看 (default "First Block") in block configuration print (Config.defaults ())


Print (' bitbucket.org ' in config) # #判断
Print (config[' bitbucket.org ' [' User ']) # #查看user的值


Second, increase, delete, change
# #删
Config.remove_section (' topsecret.server.com ') # #删除 ' topsecret.server.com ' block
Config.write (Open (' A.ini ', ' W ')) # #在创建文件 (The contents of the original file cannot be changed)

Config.remove_option (' bitbucket.org ', ' user ') # #删除 ' user ' key value under ' bitbucket.org ' block
Config.write (Open (' A.ini ', ' W ')) # #重新写入文件

# #改
Config.set (' bitbucket.org ', ' user ', ' zhangbin ') # #把 ' user ' in ' bitbucket.org ' block changed to ' Zhangbin '
Config.write (Open (' A.ini ', ' W ')) # #重新写入文件


Re (regular module)


1.findall # #查找所有 Print (Re.findall (' W.. L ', ' Hello World ')
. (dot) # #任意一个字符
^ (sharp horn) with what start
$ with what end
* Repeat for general use (. *) to match
+ The previous character appears at least once
? Front? A character can appear at most once without
{} defines how many times the preceding character appears print (Re.findall (' a{1,6}b ', ' Asdaaaab ')) # #匹配1到6个a (min. 1 max. 6 a) to B [maximum by default]
\ (backslash) to remove the special meaning of meta-characters, add ordinary characters to achieve special meaning
() represents a whole
| Or

[A-z] small A to Z
[^a-z] exclude A-Z


2.search # #同findall但只取第一个并且拿到的是位置需要group才能查看内容 Print (re.search (' AA ', ' Aaqffadaa '). Group ())

# #进阶运用方法
Ret=re.search (' (? P<ID>\D{3})/(? P<name>\d{3}) ', ' assad123/456 ')
Print (Ret.group ()) Result 123/456
Print (Ret.group (' id ')) result 123

3.match #只在字符串开头匹配 (Returns a value) view the value print (Re.match (' d ', ' DD ') with the Gourp method. Group ())
4.split # #以什么为分割 (divided into list) print (Re.split (' d|f ', ' Dafqgweef '))
5.sub # #替换 Print (re.sub (' a.*g ', ' aaaaaa ', ' Dafagegrgvdssad ')) #结果dAAAAAAvdssad6. Compile # #重复调用定义的正则匹配

Ojb=re.compile (' \.com ')
Print (Ojb.findall (' baidu.com dasasd '))


JSON (serialization module) (can communicate with other statements)


1.dumps # #json的方法存放数据
Import JSON
dic={"name": ' Zhangbin ', "Age": "23"}
F=open (' Json_write ', ' W ')
Data=json.dumps (DIC)
F.write (data)

# # #文件内容
{"Name": "Zhangbin", "Age": "23"}

2.loads # #解开json的存储方法
Import JSON
F=open (' Json_write ', ' R ')
Fw=f.read ()
D=json.loads (FW)
Print (d[' name '])
# #结果
Zhangbin


Pickle (serialization module in Python) usage is the same as JSON but supports multiple data types in Python


1.dumps
2.loads

Python common modules

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.