对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块

模块分为三种:

  • 自定义模块
  • 第三方模块
  • 内置模块

导入模块:import,导入模块时是根据那个路径作为基准来进行的呢?即:sys.path,如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append('路径') 添加

import sys,os
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)  #如何将不同目录下的PY文件进行导入前的路径准备,
# 即将要调用文件的路径加入到当前文件的临时系统路径中,然后就可以准备调用了

常用的内置模块:

1 SYS  用于提供对Python解释器相关的操作:

1

2

3

4

5

6

7

8

9

sys.argv           命令行参数List,第一个元素是程序本身路径

sys.exit(n)        退出程序,正常退出时exit(0)

sys.version        获取Python解释程序的版本信息

sys.maxint         最大的Int

sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

sys.platform       返回操作系统平台名称

sys.stdin          输入相关

sys.stdout         输出相关

sys.stderror       错误相关

2 OS 用于提供系统级别的操作

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径

os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd

os.curdir                   返回当前目录: ('.')

os.pardir                   获取当前目录的父目录字符串名:('..')

os.makedirs('dir1/dir2')    可生成多层递归目录

os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推

os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname

os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname

os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印

os.remove()                 删除一个文件

os.rename("oldname","new")  重命名文件/目录

os.stat('path/filename')    获取文件/目录信息

os.sep                      操作系统特定的路径分隔符,win下为"\\",Linux下为"/"

os.linesep                  当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"

os.pathsep                  用于分割文件路径的字符串

os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'

os.system("bash command")   运行shell命令,直接显示

os.environ                  获取系统环境变量

os.path.abspath(path)       返回path规范化的绝对路径

os.path.split(path)         将path分割成目录和文件名二元组返回

os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素

os.path.basename(path)      返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素

os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False

os.path.isabs(path)         如果path是绝对路径,返回True

os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False

os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False

os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略

os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间

os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间

import os
#print(os.getcwd()) # 获取当前工作目录
#print(os.chdir(""))
#print(os.listdir())
#print(os.stat('os1.py'))#st_atime=1570603654,上次到付时间 st_mtime=1570603654,上次修改时间 st_ctime=1570603654)创建时间
#print(os.system("dir"))
#print(os.path.split(r'D:\PycharmProjects\untitled2\old boy-module\random1.py'))#把路径和文件名分开
#print(os.path.dirname(r'D:\PycharmProjects\untitled2\old boy-module\random1.py'))#所在路径的上一级文件名
#print(os.path.basename(r'D:\PycharmProjects\untitled2\old boy-module\random1.py'))#文件名
#os.makedirs('dirname1/dirname2') #递归的方法建多层
#os.removedirs('dirname1/dirname2')#递归的方法删掉多层
#os.mkdir('dirname1') #只建一个
#os.rmdir('dirname1') #只删除一个
# a = 'D:/PycharmProjects/untitled2'
# b = 'old boy-module/os1.py'
# print(os.path.join(a,b)) #路径的拼接

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

4 random 随机

import random
# ret = random.random()#随机取浮点数
# print(ret)
# print(random.randint(1,10)) #随机取整型
# print(random.choice([11,3,22])) #多选一
# print(random.sample([11,22,33,44,55,66],3)) #多选多
# print(random.uniform(1,4))#大于1的浮点数def v_code():#产生随机密码ret=""for i in range(4):num = random.randint(0,9)alf = chr(random.randint(65,122))s = str(random.choice([num,alf]))ret+=sreturn ret
print(v_code())

5 re 正则表达式相关操作

1)字符:

  . 匹配除换行符以外的任意字符
  \w 匹配字母或数字或下划线或汉字
  \s 匹配任意的空白符
  \d 匹配数字
  \b 匹配单词的开始或结束
  ^ 匹配字符串的开始
  $ 匹配字符串的结束

2)次数:

  * 重复零次或更多次
  + 重复一次或更多次
  ? 重复零次或一次
  {n} 重复n次
  {n,} 重复n次或更多次
  {n,m} 重复n到m次

3)match,search,findall,sub,split

#正则:字符串的模糊匹配
#元字符:.^$*+?{}[]()|\
# .是通配符
import re
#print(re.findall("a..x","adsfaiexsklg")) #['aiex']
# ^ 以什么开头的意思
#print(re.findall("^a..x","adsfaiexsklg")) #[]表示字符串要以a开头的,这样就没有符合条件的了
#print(re.findall("^d...i","adsfaiexsklg"))# []
# $ 以什么结尾的意思
# print(re.findall("s..g$","adsfaiexsklg"))#['sklg']
# print(re.findall("s.l$","adsfaiexsklg"))#[]
# *和+表示迭代重复,其中*是(0-无穷),+ 是(1—无穷)
# print(re.findall("d*","adsfaieddddddxsklg")) #['', 'd', '', '', '', '', '', 'dddddd', '', '', '', '', '', '']
# print(re.findall("d+","adsfaieddddddxsklg")) #['d', 'dddddd']
# print(re.findall('alex*','tale')) #['ale']
# print(re.findall('alex+','tale')) #[]
# ? 表示(0,1)适合挑选可有可无
# print(re.findall('alex?','tale')) #['ale']
# print(re.findall('alex?','talexxx')) #['alex']
#{}是由自己定范围,可以变化出之前的*,+,?的各项
# print(re.findall('alex{3}','talexxx'))#['alexxx']
# print(re.findall('alex{5}','talexxx')) #[]
# print(re.findall('alex{1,5}','talexxx')) #['alexxx']
#[]里面的元素是或的意思,是百里挑一位,而且元字符如果在里面也是字符本身而已 除-,^(非),\(反义字符)
#  print(re.findall('q[a*z]','ksadfkq*')) #['q*']
# print(re.findall('q[a-z]','ksadfkqio*')) #['qi']
# print(re.findall('q[a-z]*','ksadfkqiik0*')) # ['qiik']
# print(re.findall('q[^a-z]','ksadfkq0*')) #['q0']
# \ 是个可以让有意义的变没意义,没意义的变有意义的魔法师
#\d 代表0-9的数字
# print(re.findall('\d','12+(34*6+2-5*(2-1))'))#['1', '2', '3', '4', '6', '2', '5', '2', '1']
# print(re.findall('\d+','12+(34*6+2-5*(2-1))')) #['12', '34', '6', '2', '5', '2', '1']
# print(re.findall('[0-9]','12+(34*6+2-5*(2-1))'))#['1', '2', '3', '4', '6', '2', '5', '2', '1']
# print(re.findall('[0-9]+','12+(34*6+2-5*(2-1))'))#['12', '34', '6', '2', '5', '2', '1']
# # \D 代表所有的非数字
# print(re.findall('\D','12+(34*6+2-5*(2-1))')) #['+', '(', '*', '+', '-', '*', '(', '-', ')', ')']
# print(re.findall('\D+','12+(34*6+2-5*(2-1))'))#['+(', '*', '+', '-', '*(', '-', '))']
# \s 空白字符 \S 非空白字符
# print(re.findall('\s','hello world')) # [' ']
# print(re.findall('\S','hello world'))# ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
# print(re.findall('\S+','hello world')) #['hello', 'world']
#\w 字母和数字字符 \W 非字母数字字符 用来挑特殊字符
# print(re.findall('\w','hello 6world')) #['h', 'e', 'l', 'l', 'o', '6', 'w', 'o', 'r', 'l', 'd']
# print(re.findall('\w+','hello 6world'))#['hello', '6world']
# print(re.findall('\W','hello -world9'))#[' ', '-']
# print(re.findall('\W+','hello *world9'))#[' *']
#\\b 挑空白和特殊字符
#print(re.findall('I\\b','helI I am Iorld')) #['I', 'I']
#print(re.findall('c\\\\l','abc\lerwt')) #['c\\l']
# | 表示或者
# print(re.findall('I|b','heblI I am Iorld'))# ['b', 'I', 'I', 'I']
# print(re.findall('lI|b','heblI I am Iorld'))#['b', 'lI']
# # ()表示整体
#print(re.findall('(abc)+','abcabcabc'))#['abc']
#research 只找一个和group连用
#re.search('\d+','sdfas34dief15').group() # 34
#(?P<>)来进行分组查询
>>> re.search('(?P<name>[a-z]+)(?P<age>\d+)','alex38angle23').group('name')
'alex'
>>> re.search('(?P<name>[a-z]+)(?P<age>\d+)','alex38angle23').group('age')
'38'
>>> re.split('[ |]','hello abc|def') #分割
['hello', 'abc', 'def']
>>> re.split('[ab]','asdabcd')
['', 'sd', '', 'cd']re.sub('\d+','R','ang23gi45') #替换
'angRgiR'
>>> re.sub('\d','R','ang23gi45')
'angRRgiRR'
>>> re.sub('\d','R','ang23gi45',2) #限定替换的个数
'angRRgi45'
>>> re.sub('\d','R','ang23gi45',2)
'angRRgi45'
>>> re.finditer('\d','sdfs6345dkfldg534jd') #将查找的结果放到迭代器里,通过next,group逐步的调用出来
<callable_iterator object at 0x000001F926A68710>
>>> ret=re.finditer('\d','sdfs6345dkfldg534jd')
>>> next(ret)
<_sre.SRE_Match object; span=(4, 5), match='6'>
>>> next(ret).group()
'3'
>>>
>>> next(ret).group()
'4'
>>> next(ret).group()
'5'
>>> re.findall('www\.baidu|163\.com','www.baidu.com')
['www.baidu']re.findall('www\.(baidu|163)\.com','www.baidu.com') #()是优先选择
['baidu']
>>> re.findall('www\.(?:baidu|163)\.com','www.baidu.com') #(?:)取消优先选择
['www.baidu.com']
# 一次有趣的筛选
>>> re.findall('abc','abcabcabc')
['abc', 'abc', 'abc']
>>> re.findall('(abc)+','abcabcabc')
['abc']
>>> re.findall('(?:abc)+','abcabcabc')
['abcabcabc']
>>> re.findall('abc+','abcabcabcopikabc')
['abc', 'abc', 'abc', 'abc']

6 序列化

Python中用于序列化的两个模块

  • json     用于【字符串】和 【python基本数据类型】 间进行转换
  • pickle   用于【python特有的类型】 和 【python基本数据类型】间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

# dic = "{'name':'angel'}"
# f = open('hello','w')
# f.write(dic) # 将字典字符串的格式写入文档中
# f_read = open('hello','r')
# date = f_read.read()
# print(date,type(date)) # {'name':'angel'} <class 'str'> 字符串
# date2 = eval(date)
# print(date2,type(date2)) # {'name': 'angel'} <class 'dict'> 字符串变字典import json
#dic={'name':'alex'}#---->{"name":"alex"}----->'{"name":"alex"}'
# i=8                 #---->'8'
# s='hello'          #---->"hello"------>"hello"
# l=[11,22]           #---->"[11,22]"
# data3 = json.dumps(dic) #通通变成双引号的字符串格式
# print(data3,type(data3))#{"name": "alex"} <class 'str'>
# f2 = open('world','w')
# f2.write(data3)
# f3 = open('world','r')
# data4 = json.loads(f3.read()) #把之前的字符串又还原成字典
# print(data4,type(data4))
#f = open('world','a')
# json.dump(s,f)
# json.dump(i,f) #是各合并的命令,将转换成字符串+写入文档二合一
# f = open('world','r')
# data5 = json.load(f)

pickle模块提供了四个功能:dumps、dump、loads、load

7 configparser

1)、获取所有节点

1

2

3

4

5

6

import configparser

config = configparser.ConfigParser()

config.read('xxxooo', encoding='utf-8')

ret = config.sections()

print(ret)

2)、获取指定节点下所有的键值对

1

2

3

4

5

6

import configparser

config = configparser.ConfigParser()

config.read('xxxooo', encoding='utf-8')

ret = config.items('section1')

print(ret)

3)、获取指定节点下所有的建

1

2

3

4

5

6

import configparser

config = configparser.ConfigParser()

config.read('xxxooo', encoding='utf-8')

ret = config.options('section1')

print(ret)

4)、获取指定节点下指定key的值

1

2

3

4

5

6

7

8

9

10

11

12

import configparser

config = configparser.ConfigParser()

config.read('xxxooo', encoding='utf-8')

v = config.get('section1', 'k1')

# v = config.getint('section1', 'k1')

# v = config.getfloat('section1', 'k1')

# v = config.getboolean('section1', 'k1')

print(v)

5)、检查、删除、添加节点

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import configparser

config = configparser.ConfigParser()

config.read('xxxooo', encoding='utf-8')

# 检查

has_sec = config.has_section('section1')

print(has_sec)

# 添加节点

config.add_section("SEC_1")

config.write(open('xxxooo', 'w'))

# 删除节点

config.remove_section("SEC_1")

config.write(open('xxxooo', 'w'))

6)、检查、删除、设置指定组内的键值对

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

import configparser

config = configparser.ConfigParser()

config.read('xxxooo', encoding='utf-8')

# 检查

has_opt = config.has_option('section1', 'k1')

print(has_opt)

# 删除

config.remove_option('section1', 'k1')

config.write(open('xxxooo', 'w'))

# 设置

config.set('section1', 'k10', "123")

config.write(open('xxxooo', 'w'))

8 XML 是实现不同语言或程序之间进行数据交换的协议

#import xml.etree.ElementTree as ET #导入xml的模块,因为名字长起了个别名
# tree = ET.parse('xml_lesson') # 拿到树结构
# root = tree.getroot() #从树结构中找到根节点
# print(root) #<Element 'data' at 0x0000016371B77778> 得到的是个对象
# print(root.tag) # data 通过调用属性获得其标签名# for i in root: #对根节点下的子节点进行遍历
#     print(i.tag ,i.attrib) # 打印出子节点的标签名和属性
#     for j in i:#对每一个具体的子节点以下的节点信息进行遍历
#         print(j.tag,j.attrib,j.text) # 通过一级一级的遍历,把完整的标签树都打印出来了
# for y in root.iter('year'): #取根节点下的year
#     print(y.tag,y.text)
#     new_year = int(y.text)+1
#     y_text = str(new_year) #将修改后的值赋予text
#     y.set('update_again','yes') #改属性
# tree.write('xml_lesson') # 最后将修改后的树结构写入原文件或新文件中# for country in root.findall('country'):#在根节点中找父节点,然后联动
#     rank = int (country.find('rank').text)#在父节点中找子节点,然后联动
#     if rank>50:
#         root.remove(country)
# tree.write('output.xml')
# import xml.etree.ElementTree as ET
# new_xml = ET.Element('namelist') #创立根节点标签
# print(new_xml)
# name = ET.SubElement(new_xml,'name',attrib={'enrolled':'yes'})#第一个参数是对象,第二个参数是标签名
# age = ET.SubElement(name, "age", attrib={"checked": "no"})
# sex = ET.SubElement(name, "sex")
# name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
# age = ET.SubElement(name2, "age")
# age.text = '19'
# et = ET.ElementTree(new_xml)#生成文档树
# et.write('test.xml',encoding='utf-8',xml_declaration=True)#把文档树写入新的XML文档
# 最终生成的XML文件如下
# <?xml version='1.0' encoding='utf-8'?>
# <namelist>
#     <name enrolled="yes">
#         <age checked="no" />
#         <sex /></name>
#     <name enrolled="no">
#         <age>19</age>
#     </name>
# </namelist>

9 logging 用于便捷记录日志且线程安全的模块

import logging
# logging.basicConfig(
#     level=logging.DEBUG,
#     filename = "logger.log",
#     filemode = "w",
#     format= "%(asctime)s%(filename)s[%(lineno)d]%(message)s"
# )
#
# logging.debug('hello')
# logging.info('world')
# logging.warning('warning message')
# logging.error('error message')
# logging.critical('critical message')# logger = logging.getLogger()
#
# fh = logging.FileHandler("test_log")
# ch = logging.StreamHandler()
#
# fm = logging.Formatter("%(asctime)s %(message)s ")
# fh.setFormatter(fm)
# ch.setFormatter(fm)
#
# logger.addHandler(fh)
# logger.addHandler(ch)
# logger.setLevel("DEBUG") #各个级别这个一定要大写
# #----#上面是设置,下面是内容
# logger.debug("hollo")
# logger.info("angel")
# logger.warning("warning")
# logger.error("error")
# logger.critical("world")

10 time

时间相关的操作,时间有三种表示方式:

  • 时间戳               1970年1月1日之后的秒,即:time.time()
  • 格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')
  • 结构化时间          元组包含了:年、日、星期等... time.struct_time    即:time.localtime()
import time
# print(time.time()) #1570458939.7151296 时间戳从1970年1月1日凌晨
# print(time.localtime()) #time.struct_time(tm_year=2019, tm_mon=10, tm_mday=7, tm_hour=22, tm_min=42, tm_sec=2, tm_wday=0, tm_yday=280, tm_isdst=0# t = time.localtime()#结构化时间
# print(t.tm_year)
# print(time.mktime(time.localtime()))#将结构化的时间转换成时间戳
#print(time.strftime('%Y-%m-%d %X',time.localtime()))#将结构化时间转换成字符串时间
# print(time.strptime("2016:12:24:17:50:36","%Y:%m:%d:%X"))
# print(time.strptime("2019:10:8:15:45:19","%Y:%m:%d:%X"))
# print(time.strptime("2016:12:24:17:50:36","%Y:%m:%d:%X"))#将字符串时间转换成结构化时间
# print(time.asctime()) #将结构化时间简单转换成字符串时间
# print(time.ctime())#将时间戳简单转换成字符串时间import datetime
print(datetime.datetime.now())

11 hashlib

import hashlib
obj = hashlib.md5()
obj.update('hello'.encode('utf8'))
print(obj.hexdigest()) #5d41402abc4b2a76b9719d911017c592

python基础之模块相关推荐

  1. python基础——使用模块

    python基础--使用模块 Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用. 我们以内建的sys模块为例,编写一个hello的模块: #!/usr/bin/env ...

  2. python基础之模块之os模块

    python基础之模块之os模块 os模块 os模块的作用: os,语义为操作系统,所以肯定就是操作系统相关的功能了,可以处理文件和目录这些我们日常手动需要做的操作,就比如说:显示当前目录下所有文件/ ...

  3. 用于生成随机数的python标准库模块是_详解Python基础random模块随机数的生成

    详解Python基础random模块随机数的生成 来源:中文源码网    浏览: 次    日期:2019年11月5日 [下载文档:  详解Python基础random模块随机数的生成.txt ] ( ...

  4. python random库生成伯努利随机数的方法_详解Python基础random模块随机数的生成

    随机数参与的应用场景大家一定不会陌生,比如密码加盐时会在原密码上关联一串随机数,蒙特卡洛算法会通过随机数采样等等.Python内置的random模块提供了生成随机数的方法,使用这些方法时需要导入ran ...

  5. Python基础之模块和包

    Python基础之模块和包 本节将介绍Python中的模块和包的概念及基本用法. 模块 简单来说模块就是一个python文件,我们可以将一些常量.函数.类等封装到一个模块中,然后在程序中使用该模块.模 ...

  6. 刻意练习:Python基础 -- Task12. 模块

    背景 我们准备利用17天时间,将 "Python基础的刻意练习" 分为如下任务: Task01:变量.运算符与数据类型(1day) Task02:条件与循环(1day) Task0 ...

  7. 带你学python基础:模块和包

    一.什么是模块 在我们平时的开发过程中,或多或少会用到 Python 的一些内置的功能,或者说,还会用到一些第三方的库,我们用到的这些 Python 的内置的功能,和一些第三方的库,就可以说是一些模块 ...

  8. 1.7 Python基础知识 - 模块初识

    在Python中有很多模块,模块对应的就是python源代码文件.模块中有Python程序自己附带的标准模块,还有很多其他人共享的第三方模块.模块中可以定义变量.函数和类.而多个功能类似的模块可以组织 ...

  9. python基础--自定义模块、import、from......import......

    自定义模块.import.from......import...... 1)模块的定义和分类 很多人学习python,不知道从何学起. 很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例 ...

  10. (更新时间)2021年3月26日 python基础知识(模块的导入)

    模块 <1>Python中的模块 在Python中有一个概念叫做模块(module),这个和C语言中的头文件以及Java中的包很类似,比如在Python中要调用sqrt函数,必须用impo ...

最新文章

  1. 电脑图片不显示缩略图怎么办
  2. Nginx特性验证-反向代理/负载均衡/页面缓存/URL重定向
  3. 9款WordPress视频插件
  4. Netty工作笔记0031---NIO零拷贝应用案例
  5. 远程办公第一天遇尴尬:企业通讯软件集体罢工、全天开视频
  6. java android 服务器_Android/Java从服务器端下载图片
  7. matlab2c使用c++实现matlab函数系列教程-sum函数
  8. 华为交换机安全端口实验
  9. 25. Magento 创建新闻模块(5)
  10. generic_make_request函数处理bio流程分析
  11. 制作OpenStack Windows Server 2016镜像
  12. matlab实现同态滤波
  13. 深信服 AC上网 行为管理设置
  14. python实现pdf转ppt_wps中pdf转成word文档 Python转换PPT为PDF
  15. ps自带磨皮滤镜插件Portraiture3PS版
  16. 微信企业号开发模式的PHP代码
  17. Android图片缓存框架 - Fresco的GenericDraweeHierarchy (五)
  18. Sketch占满MacBook200G硬盘的解决方法
  19. Win11怎么减少笔记本耗电?解决Win11耗电快的方法
  20. flex水平排列左对齐

热门文章

  1. html页面证书过期,网页证书过期怎么办
  2. 关于 mysql数据库“ERROR 1118 (42000): Row size too large.“ 的解决方法
  3. Map接口及其实现类
  4. 本立道生:必备的基础知识
  5. 编辑中的word变成只读_教大家word文档变成只读模式怎么改
  6. B2C网关支付方案介绍
  7. c语言之sizeof与strlen全
  8. 刷四百道题总结的24种常用的刷题思路
  9. 音乐播放器mplayer的简单使用
  10. excel高级筛选怎么用_Excel表格自动筛选的9个高级用法