python如何修改内置模块_Python---内置模块

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.stdin 输入相关8 sys.stdout 输出相关9 sys.stderror 错误相关

os模块

用于提供系统级别的操作:

1 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径2 os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd3 os.curdir 返回当前目录: ('.')4 os.pardir 获取当前目录的父目录字符串名:('..')5 os.makedirs('dir1/dir2') 可生成多层递归目录6 os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推7 os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname8 os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname9 os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印10 os.remove() 删除一个文件11 os.rename("oldname","new") 重命名文件/目录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不存在,返回False24 os.path.isabs(path) 如果path是绝对路径,返回True25 os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False26 os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False27 os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略28 os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间29 os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间

time & datetime模块

在Python中,通常有这几种方式来表示时间:

时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。

格式化的时间字符串(Format String)

结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)

1 importtime2

3 #print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来

4 #print(time.altzone) #返回与utc时间的时间差,以秒计算\

5 #print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",

6 #print(time.localtime()) #返回本地时间 的struct time对象格式

7 #print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式

8

9 #print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",

10 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上

11

12 #日期字符串 转成 时间戳

13 #string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式

14 #print(string_2_struct)

15 #struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳

16 #print(struct_2_stamp)

17

18 #将时间戳转为字符串格式

19 #print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式

20 #print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式

21

22

23 #时间加减

24 importdatetime25

26 #print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925

27 #print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19

28 #print(datetime.datetime.now() )

29 #print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天

30 #print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天

31 #print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时

32 #print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分

33

34 #c_time = datetime.datetime.now()

35 #print(c_time.replace(minute=3,hour=2)) #时间替换

python中时间日期格式化符号:

%y 两位数的年份表示(00-99)

%Y 四位数的年份表示(000-9999)

%m 月份(01-12)

%d 月内中的一天(0-31)

%H 24小时制小时数(0-23)

%I 12小时制小时数(01-12)

%M 分钟数(00=59)

%S 秒(00-59)

%a 本地简化星期名称

%A 本地完整星期名称

%b 本地简化的月份名称

%B 本地完整的月份名称

%c 本地相应的日期表示和时间表示

%j 年内的一天(001-366)

%p 本地A.M.或P.M.的等价符

%U 一年中的星期数(00-53)星期天为星期的开始

%w 星期(0-6),星期天为星期的开始

%W 一年中的星期数(00-53)星期一为星期的开始

%x 本地相应的日期表示

%X 本地相应的时间表示

%Z 当前时区的名称

%% %号本身

5ff2406c2c5fe56c9e2b5176da6cdb32.png

030f33cf1433a295489a87804ba3d5b2.png

hashlib模块

用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

1 importhashlib2

3 ######### md5 ########

4 hash =hashlib.md5()5 #help(hash.update)

6 hash.update(bytes('admin', encoding='utf-8'))7 print(hash.hexdigest())8 print(hash.digest())9

10

11 ######## sha1 ########

12

13 hash =hashlib.sha1()14 hash.update(bytes('admin', encoding='utf-8'))15 print(hash.hexdigest())16

17 ######### sha256 ########

18

19 hash =hashlib.sha256()20 hash.update(bytes('admin', encoding='utf-8'))21 print(hash.hexdigest())22

23

24 ######### sha384 ########

25

26 hash =hashlib.sha384()27 hash.update(bytes('admin', encoding='utf-8'))28 print(hash.hexdigest())29

30 ######### sha512 ########

31

32 hash =hashlib.sha512()33 hash.update(bytes('admin', encoding='utf-8'))34 print(hash.hexdigest())

通过对加密算法中添加自定义key再来做加密

1 importhashlib2

3 ######### md5 ########

4

5 hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))6 hash.update(bytes('admin',encoding="utf-8"))7 print(hash.hexdigest())

python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密

1 importhmac2

3 h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))4 h.update(bytes('admin',encoding="utf-8"))5 print(h.hexdigest())

random模块

1 import random2 printrandom.random()3 print random.randint(1,2)4 print random.randrange(1,10)

生成随机验证码

1 importrandom2 checkcode = ''

3 for i in range(4):4 current = random.randrange(0,4)5 if current !=i:6 temp = chr(random.randint(65,90))7 else:8 temp = random.randint(0,9)9 checkcode +=str(temp)10 print checkcode

shutil模块

shutil 是高级的文件,文件夹,压缩包处理模块。

1、shutil.copyfileobj(fsrc, fdst[, length])

将文件内容拷贝到另一个文件中

1 importshutil2

3 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))

2、shutil.copyfile(src, dst)

拷贝文件

1 shutil.copyfile('f1.log', 'f2.log')

3、shutil.copymode(src, dst)

仅拷贝权限。内容、组、用户均不变

1 shutil.copymode('f1.log', 'f2.log')

4、shutil.copystat(src, dst)

仅拷贝状态的信息,包括:mode bits, atime, mtime, flags

1 shutil.copystat('f1.log', 'f2.log')

5、shutil.copy(src, dst)

拷贝文件和权限

1 shutil.copy('f1.log', 'f2.log')

6、shutil.copy2(src, dst)

拷贝文件和状态信息

1 shutil.copy2('f1.log', 'f2.log')

7、shutil.copytree(src, dst, symlinks=False, ignore=None),shutil.ignore_patterns(*patterns)

递归的去拷贝文件夹

1 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))2

3 shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))

8、shutil.rmtree(path[, ignore_errors[, onerror]])

递归的去删除文件

1 shutil.rmtree('folder1')

9、shutil.move(src, dst)

递归的去移动文件,它类似mv命令,其实就是重命名。

1 shutil.move('folder1', 'folder3')

10、shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

创建压缩包并返回文件路径,例如:zip、tar

base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,

如:www                        =>保存至当前路径

如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/

format:压缩包种类,“zip”, “tar”, “bztar”,“gztar”

root_dir:要压缩的文件夹路径(默认当前目录)

owner:用户,默认当前用户

group:组,默认当前组

logger:用于记录日志,通常是logging.Logger对象

1 #将 /Users/lidong/Downloads/test 下的文件打包放置当前程序目录

2 importshutil3 ret = shutil.make_archive("www", 'gztar', root_dir='/Users/lidong/Downloads/test')4

5

6 #将 /Users/lidong/Downloads/test 下的文件打包放置 /Users/lidong/目录

7 importshutil8 ret = shutil.make_archive("/Users/lidong/www", 'gztar', root_dir='/Users/lidong/Downloads/test')

shutil 对压缩包的处理是通过调用ZipFile 和 TarFile两个模块来进行的

1 importzipfile2

3 #压缩

4 z = zipfile.ZipFile('laxi.zip', 'w')5 z.write('a.log')6 z.write('data.data')7 z.close()8

9 #解压

10 z = zipfile.ZipFile('laxi.zip', 'r')11 z.extractall()12 z.close()

1 importtarfile2

3 #压缩

4 tar = tarfile.open('your.tar','w')5 tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log')6 tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log')7 tar.close()8

9 #解压

10 tar = tarfile.open('your.tar','r')11 tar.extractall() #可设置解压地址

12 tar.close()

re模块

1 '.'默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行2 '^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)3 '$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以4 '*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a']5 '+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']6 '?'匹配前一个字符1次或0次7 '{m}'匹配前一个字符m次8 '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']9 '|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'

10 '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c11

12

13 '\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的14 '\Z'匹配字符结尾,同$15 '\d' 匹配数字0-9

16 '\D'匹配非数字17 '\w' 匹配[A-Za-z0-9]18 '\W' 匹配非[A-Za-z0-9]19 's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'

20

21 '(?P...)' 分组匹配 re.search("(?P[0-9]{4})(?P[0-9]{2})(?P[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}

1 re.match    从头开始匹配2 re.search    匹配包含3 re.findall 把所有匹配到的字符放到以列表中的元素返回4 re.splitall 以匹配到的字符当做列表分隔符5 re.sub 匹配字符并替换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值