标签:
模块让你能够有逻辑地组织你的Python代码段。
把相关的代码分配到一个 模块里能让你的代码更好用,更易懂。
模块也是Python对象,具有随机的名字属性用来绑定或引用。
简单地说,模块就是一个保存了Python代码的文件。模块能定义函数,类和变量。模块里也能包含可执行的代码。
想使用Python源文件,只需在另一个源文件里执行import语句,语法如下:
import module1[, module2[,... moduleN]
Python的from语句让你从模块中导入一个指定的部分到当前命名空间中。语法如下:
from modname import name1[, name2[, ... nameN]]
把一个模块的所有内容全都导入到当前的命名空间也是可行的,使用如下:
from modname import *
Python的标准库中的os模块包含普遍的操作系统功能。
1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 2 os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd 3 os.curdir 返回当前目录: (‘.‘) 4 os.pardir 获取当前目录的父目录字符串名:(‘..‘) 5 os.makedirs(‘dirname1/dirname2‘) 可生成多层递归目录 6 os.removedirs(‘dirname1‘) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 7 os.mkdir(‘dirname‘) 生成单级目录;相当于shell中mkdir dirname 8 os.rmdir(‘dirname‘) 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname 9 os.listdir(‘dirname‘) 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 10 os.remove() 删除一个文件 11 os.rename("oldname","newname") 重命名文件/目录 12 os.stat(‘path/filename‘) 获取文件/目录信息 13 os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/" 14 os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n" 15 os.pathsep 输出用于分割文件路径的字符串 16 os.name 输出字符串指示当前使用平台。win->‘nt‘; Linux->‘posix‘ 17 os.system("bash command") 运行shell命令,直接显示 18 os.environ 获取系统环境变量 19 os.path.abspath(path) 返回path规范化的绝对路径 20 os.path.split(path) 将path分割成目录和文件名二元组返回 21 os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素 22 os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 23 os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False 24 os.path.isabs(path) 如果path是绝对路径,返回True 25 os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False 26 os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False 27 os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 28 os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间 29 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
sys 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分。
1 sys.argv 命令行参数List,第一个元素是程序本身路径 2 sys.exit(n) 退出程序,正常退出时exit(0) 3 sys.version 获取Python解释程序的版本信息 4 sys.maxint 最大的Int值 5 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 6 sys.platform 返回操作系统平台名称 7 sys.stdout.write(‘please:‘) 8 val = sys.stdin.readline()[:-1]
用于序列化的两个模块
json:用于字符串和python数据类型间进行转换
pickle:用于python特有的类型和python的数据类型间进行转换
json模块提供了四个功能:dumps dump loads load
pickle模块提供了四个功能: dumps dump loads load
dumps把Python基本数据类型转换成字符串形式,loads把字符串形式转换成基本数据类型,dump将数据通过特殊的形式转换为所有语言都认识的字符串,并写入文件,load把文件打开从字符串转换成数据类型
dumps将数据通过特殊的形式转换为只用python语音能识别的字符串,loads把字符串形式转换成基本数据类型,dump将数据通过特殊的形式转换为只有python语音认识的字符串,并写入文件,load把文件打开从字符串转换成数据类型
由此得出:json更加适合跨语言,pickle仅适用于python
实例:
1 import json 2 3 dic = {‘k1‘: ‘v1‘} 4 print(dic,type(dic)) 5 # 将python基本数据类型转化成字符串形式 6 result = json.dumps(dic) 7 print(result,type(result)) 8 9 s1 = ‘{"k1": 123}‘ 10 # 将python字符串形式转化成基本数据类型 11 dic = json.loads(s1) 12 print(dic,type(dic)) 13 14 15 li = [11,22,33] 16 json.dump(li,open(‘db‘,‘w‘)) 17 18 li = json.load(open(‘db‘,‘r‘)) 19 print(type(li),li) 20 21 22 #输出结果 23 {‘k1‘: ‘v1‘} <class ‘dict‘> 24 {"k1": "v1"} <class ‘str‘> 25 {‘k1‘: 123} <class ‘dict‘> 26 <class ‘list‘> [11, 22, 33]
1 import pickle 2 li = [11,22,33] 3 r = pickle.dumps(li) 4 print(r) 5 6 result = pickle.loads(r) 7 print(result) 8 9 li = [11,22,33] 10 pickle.dump(li, open(‘db‘, ‘wb‘)) 11 12 13 #输出结果 14 b‘\x80\x03]q\x00(K\x0bK\x16K!e.‘ 15 [11, 22, 33]
time模块提供各种操作时间的函数说明:一般有两种表示时间的方式:
第一种是时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的
第二种以数组的形式表示即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同
year (four digits, e.g. 1998)
month (1-12)
day (1-31)
hours (0-23)
minutes (0-59)
seconds (0-59)
weekday (0-6, Monday is 0)
函数用法:
1 time.time() #返回当前时间的时间戳 2 time.ctime() #输出当前系统时间 3 time.gmtime(time.time()-86640) #将时间戳转换成struct_time格式 4 time.gmtime(time.time()-86640) #将时间戳转换成struct_time格式 5 time.localtime(time.time()-86640) #将时间戳转换成struct_time格式,但返回 的本地时间 6 time.mktime(time.localtime()) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式 7 time.sleep(4) #sleep 8 time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) #将struct_time格式转成指定的字符串格式 9 time.strptime("2016-01-28","%Y-%m-%d") #将字符串格式转换成struct_time格式
常见用法:
1 datetime.date.today() #输出格式 2016-06-10 2 datetime.date.fromtimestamp(time.time()-864400) #将时间戳转成日期格式
Directive | Meaning | Notes |
---|---|---|
%a |
Locale’s abbreviated weekday name. | |
%A |
Locale’s full weekday name. | |
%b |
Locale’s abbreviated month name. | |
%B |
Locale’s full month name. | |
%c |
Locale’s appropriate date and time representation. | |
%d |
Day of the month as a decimal number [01,31]. | |
%H |
Hour (24-hour clock) as a decimal number [00,23]. | |
%I |
Hour (12-hour clock) as a decimal number [01,12]. | |
%j |
Day of the year as a decimal number [001,366]. | |
%m |
Month as a decimal number [01,12]. | |
%M |
Minute as a decimal number [00,59]. | |
%p |
Locale’s equivalent of either AM or PM. | (1) |
%S |
Second as a decimal number [00,61]. | (2) |
%U |
Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. | (3) |
%w |
Weekday as a decimal number [0(Sunday),6]. | |
%W |
Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. | (3) |
%x |
Locale’s appropriate date representation. | |
%X |
Locale’s appropriate time representation. | |
%y |
Year without century as a decimal number [00,99]. | |
%Y |
Year with century as a decimal number. | |
%z |
Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. | |
%Z |
Time zone name (no characters if no time zone exists). | |
%% |
A literal ‘%‘ character. |
1.简单的将日志打印到屏幕
1 import logging 2 3 logging.debug(‘This is debug message‘) 4 logging.info(‘This is info message‘) 5 logging.warning(‘This is warning message‘) 6 7 # 屏幕上打印: 8 WARNING:root:This is warning message 9 # 10 # 默认情况下,logging将日志打印到屏幕,日志级别为WARNING; 11 # 日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。
2.将日志输出到文件中
1 import logging 2 3 logging.basicConfig(filename=‘example.log‘,level=logging.INFO, 4 format=‘%(asctime)s %(message)s‘, datefmt=‘%m/%d/%Y %I:%M:%S %p‘) 5 logging.debug(‘This message should go to the log file‘) 6 logging.info(‘So should this‘) 7 logging.warning(‘And this, too‘) 8 9 10 #文件中内容 11 06/10/2016 03:29:02 PM So should this 12 06/10/2016 03:29:02 PM And this, too 13 14 #这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说, 15 # 只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 16 # 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。
Level | When it’s used |
---|---|
DEBUG |
Detailed information, typically of interest only when diagnosing problems. |
INFO |
Confirmation that things are working as expected. |
WARNING |
An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR |
Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL |
A serious error, indicating that the program itself may be unable to continue running. |
标签:
原文地址:http://www.cnblogs.com/mxzheng/p/5573731.html