pycharm使用技巧
1、设置新建文价夹时自动生成的代码或注释行
file—>settings—>File and Code Templates—>Python Script
2、设置快捷自动生成代码
file—>settings—>Live Templates applicate in pathon
3、修改函数的颜色
file—>settings—>editor—>color scheme—>python—>function call
4、分屏
file—>settings—>keymap—>查询split关键字,设置快捷键
vertically 纵向切割 Horizontally 横向切割
5、版本管理:SVN CVS GIT
右键选择文件夹—>选择local history—>show history—>选择需要的版本—>右键选择revert进行回滚
6、快捷键
1、补全main,Ctrl+J
2、快速切换到下一行:shift+enter
7、注释
ctrl + /
8、运行
右键,选择Execute Line in python console , 在Python Console 中运行选中语句
基础语法
type()类型
print(type(3))
除法 取商
print(9/4)
print(9//4)
除法 取余数
print(9%4)
查看关键字
import keyword
print(keyword.kwlist)
变量必须赋初始值
a=100
求a内存id地址
print(id(a))
a = a +1
print(a)
a+=1
print(a)
a-=1
print(a)
转义字符:\n 换行 \t 制表符 需要在\之前再加上一个\ 或者用/代替\
print('c:\\n\\a')
print('c:/n/a')
r 可以取消转义
print(r'c:\n\a')
for _ in range(n)
# _ 是占位符, 表示不在意变量的值 只是用于循环遍历n次
字符
#三个单引号、三个双引号可以在方法或者函数中作为注释,也可以作为换行
print("""111111
22222
33333
44444""")
#字符串*数字 = 字符串显示n次
print('a'*6)
#字符串的下标是从0开始
str1 = 'abcdefg'
#打印c
print(str1[2])
#打印g
print(str1[-1])
# 字符串的切片 左闭右开
# 打印cd
print(str1[2:4])
#前六位,每两位取一位
print(str1[:6:2])
# 翻转
print(str1[::-1])
# 取后10个数
print(str1[-10:])
# 打印到最后一位
print(str1[2:])
# 对tuple进行截取 (1,2,3)
print((1,2,3,4,5,6)[:3])
# len()返回字符串的长度
print(len(str1))
# index()返回某个字符在字符串的下标
print(str1.index('e'))
# 字符串属于不可变对象,列表是个可变对象,也就是字符串不可以通过下标修改字符串的某个字符
# str1[0] = 'qq' 错误
# 如果要修改字符串,只能全部该,重新赋值
str1 = 'qq'
# 判断子字符串在字符串中的个数
str1 = input('请输入一个字符串:\n')
tr2 = input('请输入一个子字符串:\n')
ncount = str1.count(str2)
print(ncount)
# 移除字符串头尾指定的字符
str = "00000003210Runoob01230000000"
# 去除首尾字符 0,结果:3210Runoob0123
print str.strip( '0' )
str2 = " Runoob "
# 去除首尾空格,结果:Runoob
print str2.strip()
位运算
# 按位与 &
# 0&0=0; 0&1=0; 1&0=0; 1&1=1
# 按位或
# 0|0=0; 0|1=1; 1|0=1; 1|1=1
# 按位异或
# 0^0=0; 0^1=1; 1^0=1; 1^1=0
# 按位取反
# ~x = -x-1
列表
# append 添加值到列表的末尾
list1 = [1,2,3,4,5,6]
list1.append(7)
print(list1)
# insert(下标位置,添加的值)
list1.insert(1,36)
# extend() 对列表的拼接
list1.extend('abc')
list1.extend([33,99])
print(list1)
# 列表的删除
# pop
# 删除最后一位
list1.pop()
# 删除指定下标值的值
list1.pop(1)
# 接收删除的值
a = list1.pop()
print(a)
print(list1)
# remove
# 根据值进行删除,当有多个值时,删除第一个
list1.remove(7)
print(list1)
# del
del list1[0]
print(list1)
# 列表排序
list2 = [23,34,-1,67,2,1]
# 翻转
print(list2[::-1])
print(list2)
# 临时排序
print(sorted(list2))
# 永久排序
list2.sort()
print(list2)
# 倒序
list2.sort(reverse=True)
print(list2)
# 连接
con = '-'
print(con.join(list))
元组
# 元组是不可变对象,其它与列表一样 即不能进行增删改
tuple1 = (10,20,30,40,50)
# 使用切片
print(tuple1[0:2])
# 只有一个元组时
tuple2 = (10,)
print(type(tuple2))
# 如果元组中有子列表,子列表中的值可进行更改
tuple3 = (10,20,[30,40,50])
tuple3[2][0] = 99
print(tuple3)
字典
# 键必须不可变,可以用数字,字符串或元组充当,用列表就不行
from filecmp import *
dict = {'A':'apple','B':'book'}
# 删除字典里的key
del dict['A']
print(dict)
# 清空字典里所有条目
dict.clear()
print(dict)
# 删除字典
del dict
print(dict)
# 比较两个字典元素
dict1 = {'aa':11,'bb':22}
dict2 = {'aa':33,'bb':44}
# 以列表返回可遍历的(键, 值) 元组数组
print(dict1.items())
# 以列表返回一个字典所有的键
print(dict1.keys())
# 把字典dict2的键/值对更新到dict里
dict1.update(dict2)
print(dict1)
# 查询某个key对应的值
print(dict1.get('aa'))
列表生成式
# 对数据进行操作的表达式写前面,数据处于后面
# eg:计算1至10的平方
list = [x*x for x in range(1,11)]
print(list)
# for条件后加入if条件进行筛选 此处if后不能带else,if筛选的是符合表达式计算的数据
list = [x * x for x in range(1,11) if x % 2 == 0]
print(list)
# for条件前加入if条件进行处理,此处if后必须带else,if处理的是进行表达式计算后的值
list = [x if x%2 == 0 else -x for x in (1,11)]
print(list)
# 双层循环
list = [m + n for m in 'AB' for n in 'CD']
print(list)
# 列出当前目录下所有文件和文件名
list = [d for d in os.listdir('.')]
print(list)
# 接收多个变量,如字典型的key-value
d = {"me":'yaxin',"sister":'yapin',"brother":'jiale'}
list = [relation + '=' + name for relation,name in d.items()]
print(list)
格式化
print('hello,%s,%s' % ('雅馨','雅萍'))
print('hello,{0},{1}'.format('雅馨','雅萍'))
myname = '雅馨'
sistername = '雅萍'
age = 24.555
print(f'hello,{myname},{age:.1f},{sistername}')
python的内置函数
ord() 函数
# ord() 函数是 chr() 函数(对于 8 位的 ASCII 字符串)的配对函数,它以一个字符串(Unicode 字符)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值
ord(a)
chr(97)
时间
import time
# time.strftime(时间输出格式,可选时间对象),格式化时间,返回可读字符串表示的当地时间
'''
%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 当前时区的名称
%% %号本身
'''
time.strftime("%y%m%d",time.localtime())
# 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。 如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于 asctime(localtime(secs)) 格式:Tue Feb 17 10:00:18 2013
print(time.ctime(time.time()))
# time.localtime 格式化时间戳为本地的时间
print(time.asctime(time.localtime(time.time())))
# time.gmtime 将一个时间戳转换为UTC时区(0时区)的struct_time 格式:time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=2, tm_min=55, tm_sec=45, tm_wday=3, tm_yday=98, tm_isdst=0
print(time.asctime(time.gmtime(time.time())))
# 计算程序所需要的使用的时间
import time
start = time.process_time()
for i in range(10000):
print(i)
end = time.process_time()
print(start)
print(end)
print('different is %6.3f' % (end - start))
# dateutil
# 1、安装 pip install python-dateutil
# 2、parser方法 字符串可以很随意,可以用时间日期的英文单词,可以用横线、逗号、空格等做分隔符
# 没指定时间默认是0点,没指定日期默认是今天,没指定年份默认是今年
# 3、rrule方法 格式:rrule(self, freq, dtstart=None, interval=1, wkst=None, count=None, until=None, bysetpos=None,bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, cache=False)
# freq:可以理解为单位。可以是 YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY。即年月日周时分秒。
# dtstart,until:是开始和结束时间。
# wkst:周开始时间。
# interval:间隔。
# count:指定生成多少个。
# byxxx:指定匹配的周期。比如byweekday=(MO,TU)则只有周一周二的匹配。byweekday可以指定MO,TU,WE,TH,FR,SA,SU。即周一到周日
from dateutil.parser import *
dt = parser.parse("Aug 12 2012 00:00AM")
print(dt)
print(parser.parse("Wed, Aug 12"))
print(parser.parse('2021-08-12'))
print(parser.parse('2021,08,12'))
# fuzzy开启模糊匹配,过滤掉无法识别的时间日期字符
print(parser.parse('I think 2021-08-12 08:00:00 is a fun day',fuzzy = True))
from dateutil.rrule import *
# 2013-08-01到2013-08-07每日
print(list(rrule(DAILY,dtstart=parse('2021-08-01'),until=parse('2021-08-12'))))
# 间隔为3
print(list(rrule(DAILY,interval=3,dtstart=parse('2021-08-01'),until=parse('2021-08-12'))))
# 只生成3个
print(list(rrule(DAILY,count=3,dtstart=parse('2021-08-01'),until=parse('2021-08-12'))))
# 只匹配周一周二的
print(list(rrule(DAILY,byweekday=(MO,TU),dtstart=parse('2021-08-01'),until=parse('2021-08-12'))))
# 按月为单位
print(list(rrule(MONTHLY,dtstart=parse('2021-08-01'),until=parse('2021-08-12'))))
call()
该方法的功能类似于在类中重载()运算符,使得类实例对象可以像调用普通函数一样,以"对象名()"的形式使用,每个类方法都属于可调用对象,因此也具有__call__属性
class Manager:
# 定义__call__方法
def __call__(self,name=None):
print("调用__call__()方法",name)
manager = Manager()
mamger("我是call方法")
结果:
调用__call__()方法 我是call方法
exec
执行储存在字符串或文件中的 Python 语句 返回值永远为 None
json模块
import json
data1 = {
"aac003" : "tom" ,
"tel" : "13445677890" ,
"crm001" : "111" ,
"crm002" : "222"
}
print(type(data1))
# loads()将json格式转换为字典
data2 = json.loads(data1)
print(data2)
print(type(data2))
# 将字典转换为json格式
data3 = json.dumps(data2)
print(data3)
print(type(data3))
# load 和 loads 的区别,前者是从文件中读取json文本,后者是在变量中读取
with open('d:/json3.txt') as file1:
temp3 = json.load(file1)
print(type(temp3))
# dump 与 dumps 的区别,前者是将字典转换为json数据写入文件中,后者是直接在代码中将字典转换成json格式
with open('d:/json30.txt') as file2:
temp4 = json.dump(data2,file2)
file2.seek(0)
print(file2.read())
# python 数据格式
- 表示一个数字:2.0
- 表示一个字符串:“Hello”
- 表示一个数组:
["sister":"yapin"]
[["sister",["brother",16]]]
[["sister":"yapin"],["brother":"jiale"]]
[{"name":"yapin","relation":"sister"},{"name":"jiale","reletion":"brother"}]
- 表示一个对象:
{"name":"yapin","relation":"sister","age":18,"love":{"mother":"zhenyu","brother":"jiale"}}
函数
# 形式参数 : 没有返回值的函数,a,b是形式参数
def sum(a,b):
print(a+b)
# 实参 33,69是实际参数
sum(33,69)
# return可以以元组的形式返回多个值
def func1(a):
return a*a,a+a,a**a
# 位置参数 *args 代表 0-n个
def fun2(a,b,*args):
print(a,b,*args)
fun2(22,33)
fun2(22,33,44,55)
def fun3(*args,a,b):
print(*args,a,b)
# 不会拆包
print(args,a,b)
fun3(22,33,44,55,a=66,b=77)
# 关键字参数,会存放为一个字典 必须放在位置参数后面
def fun4(a,**kwargs):
print(a,kwargs)
fun4(10,name='天怡')
# 内置函数 BIF
print()
len()
type()
# 匿名函数 lambda
# MAXIMUM和MINIMUM 没有函数名
MAXIMUM = lambda x, y: (x > y) * x + (x < y) * y
MINIMUM = lambda x, y: (x > y) * y + (x < y) * x
if __name__ == '__main__':
a = 10
b = 20
print('The largar one is %d' % MAXIMUM(a, b))
print('The lower one is %d' % MINIMUM(a, b))
a = ' ABC DEFG '
# 去掉字符串前后的空格,或者其他指定的值
b = a.strip()
print(b)
b1 = '--------ABC---DEFG---------'
# 去掉字符串前后的-
b2 = b1.strip('-')
b3 = 'EFGHJEFGHJEDGHJ'
# 字符串当中,出现了几个G
print(b3.count('G'))
id = '362426199009898909'
if id.endswith('09'):
print('最后的数')
else:
print('不是最后的数')
if id.startswith('3624'):
print('开始的位数')
else:
print('不是开始的数')
# id.isdigit() 纯数字
# id.isalpha() 纯字母
# split() 切割
# ''.join() 字符串拼接
# replace() 替换
异常机制/操作日志
- 配置文件输出日志:
# 读取日志配置文件内容
logging.config.fileConfig('logging.conf')
# 创建一个日志器logger
logger = logging.getLogger('simpleExample')
# 日志输出
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
配置文件logging.conf:
[loggers]
keys=root,simpleExample
[handlers]
keys=fileHandler,consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=fileHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
args=(sys.stdout,)
level=DEBUG
formatter=simpleFormatter
[handler_fileHandler]
class=FileHandler
args=('logging.log', 'a')
level=ERROR
formatter=simpleFormatter
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
class = logging.Formatter
datefmt=
- 代码输出日志:
import logging
import time
# 可以通过这个模块将报错信息写入到文件中 traceback.format_exc() time
import traceback
# level表示日志的记级别(此级别以上的级别均记录进日志),filename表示日志的路径,filemode表示日志的写入模式
# 设置日志格式
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
# 设置日期格式
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
logging.basicConfig(level=logging.DEBUG,filename='d:/loginfo11.log',filemode='a',format=LOG_FORMAT,datefmt=DATE_FORMAT)
logging.info('This is a info')
logging.debug('This is a debug')
logging.warning('This is a warning'+' '+time.strftime('%y-%m-%d %H:%M:%S')+' '+traceback.format_exc())
logging.error('This is a error',exc_info=True, stack_info=True, extra={'user': 'Tom', 'ip':'47.98.53.222'})
logging.critical('This is a critical')
logging.log(logging.CRITICAL,"This is a critical")
正则表达式
# 根据一定的规则提取字符串
import re
str1 = 'abbcdeaffabqdefg'
# re.findall(正则表达式,需要进行正则处理的字符串)
# .表示匹配某个字符后面的任意一个字符
print(re.findall('b.',str1))
# 如果正则外面有括号,则表示只打印它自己的内容
print(re.findall('b(.)',str1))
# ab*表示a后面有 0-n个b
print(re.findall('ab*',str1))
#ab+表示一个字符a后面有 1-n个b
print(re.findall('ab+',str1))
# ab?表示一个字符a后面有 0-1个b
print(re.findall('ab?',str1))
# .*?放一起使用, A(.*?)B 匹配A到B之间的字符串
str2 = '瀚海阑干百丈冰'
print(re.findall('干(.*?)冰',str2))
# 如果A(.*?),后面没有B这个值,则进行偷懒匹配,尽可能少配
print(re.findall('瀚(.*?)',str2))
# .* 与 .*? 的区别:前者是贪婪匹配,后者是偷懒匹配
print(re.findall('瀚(.*)冰',str2))
print(re.findall('瀚(.*)',str2))
# .? 匹配一个字符
# 瀚和冰之间有4个字符,无法确定是哪个,所以返回空
print(re.findall('瀚(.?)冰',str2))
print(re.findall('瀚(.?)',str2))
# \w 匹配字母,数字,下划线
str3 = 'abc&1_de'
# 四位四位取符合匹配要求的值
print(re.findall('\w{4}',str3))
# \W{n} 匹配字母,数字,下划线以外的值
str3_1 = '!@1#$@2#3$%4&*%^66!78^(&**532$%%^)&'
print(re.findall('\W{3}',str3_1))
# \s 匹配空字符串,\t制表符,\n换行符
str9 = '''
123 123 123 12312 23423423
12313
123131231
'''
print(re.findall('\s{3}',str9))
# \S 匹配除空字符串以外的字符
print(re.findall('\S{3}',str9))
# \d 匹配数字
str9_1 = '12ab3123wegefvmrtbfvd3112312ebv'
print(re.findall('\d{3}',str9_1))
# ^匹配开头 $匹配结尾
list1 = ['abcde','deabc','dabce']
for one in list1:
# 打印abc开头的字符串
if re.findall('^abc',one):
print(one)
# 打印abc结尾的字符串
if re.findall('abc$',one):
print(one)
# 打印abc为中间的
if not re.findall('^abc',one) and not re.findall('abc$',one):
print(one)
# re.I 不区分大小写
str11 = 'anCdefg'
print(re.findall('abc',str11,re.I))
# re.S 查找多行
文件处理
"""
ASCII:7位表示一个字符,最高位为0,只能表示128个字符
ISO8858:8位表示一个字符,能表示256个字符,兼容ASCII,不兼容Unicode
Unicode:定长编码,2个字节表示一个字符
UTF-8:变长编码,1-4字节表示1个字符,英文1个字节,汉字3个字节,是 Unicode的实现
GB2312、GBK、GB18030:兼容ISO8859-1,英文1个字节,汉字2个字节
"""
# 文件操作语法规则 file = open(filename[,mode,encoding])
# 读取文件,以列表展示
import os
file = open('a.txt','r')
print(file.readlines())
file.close()
# 替换原有内容为write中的内容
file = open('b.txt','w')
file.write('hello')
file.close()
# 往b文件中追加write中的内容
file = open('b.txt','a')
file.write('python')
# 光标回到某个字节处 seek(m,n) m:光标向后偏移几位,0 表示文件头,
# n 默认为 0,也可以为 1 或 2 ,只有在rb模式才有效,2表示从尾部移动,1从当前位置移动,0从开头移动
file.seek(2)
file.close()
# 以二进制形式打开文件,将src_file复制给target_file
src_file = open('logo.png','rb')
target_file = open('copylogo.png','wb')
target_file.write(src_file.read())
target_file.close()
src_file.close()
# 读取一行
file = open('b.txt','r')
print(file.readline())
file.close()
# 读取所有,并将对象放入列表返回
file = open('b.txt','r')
print(file.readlines())
file.close()
# 写入
file = open('c.txt','a')
print(file.write())
file.close()
# 将字符串列表写入文本文件,不添加换行符
file = open('c.txt','a')
lst = ['java','python','c','go']
print(file.writelines(lst))
file.close()
# 将文件指针移动到新的位置,offset(字节数)表示相对于whence的位置,offset为正往结束方向移动,为负往开始方向移动
# whence:0 从文件头开始计算(默认值) 1 从当前位置开始计算 2 从文件尾开始计算
file.seek(2)
print(file.read())
# 返回文件指针的当前位置,从0开始
print(file.tell())
file.close()
# flush 把缓冲区的内容写入文件,但不关闭文件
file = open('d.txt','a')
file.flush()
file.write('world')
file.close()
# with语句 上下文管理器-->实现了__enter__()和__exit__()方法
# 离开时自动调用__exit__()方法 不论什么原因跳出with,都能确保文件正确的关闭,以此来达到释放资源的目的
with open('a.txt','r') as file:
print(file.read())
# os 调用系统的一些运行程序、可执行文件
os.system('notepad.exe')
# os.startfile('D:\\tempsoft\\qq.exe')
系统级别文件处理(os)
import os
# 返回当前的工作目录
os.getcwd()
# 返回指定路径下的文件和目录信息
lst = os.listdir('../chap12')
print(lst)
# 创建目录
os.mkdir('newdir')
# 创建多级目录
os.makedirs('A/B/C')
# 删除目录
os.rmdir('newdir')
# 删除多级目录
os.removedirs('A/B/C')
# 将path设置为当前工作目录
# os.chdir('path')
# 获取文件或目录的绝对路径
print(os.path.abspath('demo6.py'))
# 用于判断文件或目录是否存在
print(os.path.exists('demo6.py'),os.path.exists('demo16.py'))
# 将目录与目录或者文件名拼接起来
print(os.path.join('D:\\Python','demo14.py'))
# 分离文件名或扩展名
print(os.path.split('D:\\python\\demo14.py'))
# 分离文件名和后缀名
print(os.path.splitext('demo14.py'))
# 从一个目录中提取文件名
print(os.path.basename('D:\\python\demo14.py'))
# 从一个路径中提取文件路径,不包括文件名
print(os.path.dirname('D:\\python\demo14.py'))
# 判断是否为路径
print(os.path.isdir('D:\\python\demo14.py'))
'''
os.environ : 获取环境变量 环境变量是程序和操作系统之间的通信方式,返回一个字典
使用场景 :有些字符不宜明文写进代码里,比如数据库密码,个人账户密码,如果写进自己本机的环境变量里,程序用的时候通过 os.environ.get() 取出来 就行
'''
# WINDOWS下常见字段:
# 获取主目录下的所有key
print(os.environ.keys())
# 获取当前用户主目录
print(os.environ['HOMEPATH'])
# 获取临时目录路径
print(os.environ['TEMP'])
# 获取可执行文件
print(os.environ['SYSTEMROOT'])
# 获取机器名
print(os.environ['LOGONSERVER'])
# 设置提示符
# print(os.environ['PROMPT'])
# Linux下常见字段
# 当前使用用户
print(os.environ['USER'])
# 路径扩展的结果排序时的字母顺序
print(os.environ['LC_COLLATE'])
# 使用shell的类型
print(os.environ['SHELL'])
# 使用的语言
print(os.environ['LAN'])
# ssh的执行路径
print(os.environ['SSH_AUTH_SOCK'])
# 当key存在时返回相应的value,当不存在时返回默认值
os.environ.get(key,'default')
#设置环境变量
os.environ['环境变量名称']='环境变量值' #其中key和value均为string类型
os.putenv('环境变量名称', '环境变量值')
os.environ.setdefault('环境变量名称', '环境变量值')
# 修改环境变量
os.environ['环境变量名称']='新环境变量值'
# 获取系统环境变量
os.environ['环境变量名称']
os.getenv('环境变量名称')
os.environ.get('环境变量名称', '默认值') #默认值可给可不给,环境变量不存在返回默认值
# 删除系统环境变量
del os.environ['环境变量名称']
del(os.environ['环境变量名称'])
# 判断系统环境变量是否存在
'环境变量值' in os.environ # 存在返回 True,不存在返回 False
# 使用os.system(cmd)即可在python中使用linux命令
os.system('命令')
glob模块
glob是一个古老的unix程序,用来匹配路径文件名(pathname模式匹配),python自带一个glob模块
一、glob模式匹配规则
二、函数使用
glob.glob函数 : 此函数返回一个符合glob匹配的pathname的list,返回结果可能是空,符号链接文件也可能会包含在返回结果中
eg:
import glob
glob.glob('t*') ---->返回文件名第一个字符为t的所有文件名,不包含文件路径
glob.glob('./t*') ------>返回文件名第一个字符为t的所有文件名,返回格式为 ./+文件名,即与规则保持一致
glob.glob('~/test/t*') ----->返回文件名第一个字符为t的所有文件名,返回格式为 /test/ + 文件名 ,~扩展不支持
glob.glob('/home/xixi/test/t*') ----->返回文件名第一个字符为t的所有文件名,返回格式为 /home/xixi//test/ + 文件名
eg: 支持**规则,配合recursive=True使用可深入到路径的子目录中进行匹配,展示更详细的子目录文件
glob.glob('**/*.py',recursive=True)
glob.iglob函数 : 迭代器,规则与参数和glob函数一致,不同的是,glob一次性返回所有的遍历结果,而iglob一个一个返回结果
eg:
for pn in glob.iglob('**/*.py',recursive=True):
PRINT(PN)
glob.escape函数 : 离开glob规则特别符号的原有含义,返回的是一个glob规则,将 *,?,[ 这三个特殊符号转换成可以去匹配含有这三个特殊符号字符串的glob规则
Excel表格处理
# 实例化一个excel
excel = xlwt.Workbook()
#新建一个sheet
worksheet = excel.add_sheet('excel的名字')
# 行索引下标,列索引下标,值 索引下标从0开始
worksheet.write(0,1,'目录')
worksheet.write(1,1,'章节')
excel.save(f'excel存放地址')
# 读取excel xlrd只支持xls文件,不支持xlsx文件
data = xlrd.open_workbook(f'excel存放地址')
# 读取第一个sheet
sheet1 = data.sheets()[0]
# sheet1.nrows 获取有效行数
for i in range(1,sheet1.nrows):
# 获取单元格内容
print(sheet1.cell_value(i,0),sheet1.cell_value(i,1))
from openpyxl import Workbook
wb = Workbook()
# 创建excel文件
worksheet = wb.create_sheet('data2')
# 写入数据
worksheet.append(['username','password'])
for i in range(100):
worksheet.append([f'testuser{i}','123456'])
#save file
wb.save('./data2.xlsx')
# 读取文件数据 openpyxl 不支持xls文件,仅支持xlsx文件
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet
wb = load_workbook('data2.xlsx')
#print(wb.sheetnames)
ws:Worksheet = wb['data2']
test_data = []
for row in ws.values:
test_data.append(row)
print(test_data)
# 修改表格内容
wb = load_workbook(file_path)
# wb[sheet名称]
sheet = wb['Sheet1']
# cell(行,列)
sheet.cell(row=1, column=1).value = 'mulu'
sheet.cell(row=2, column=1_.value = 'zhangjie'
wb.save(file_path)
CSV文件处理
import csv
# 如果原文件存在数据,则会被覆盖
# 将数据写入csv文件
with open('./data.csv',mode='w',newline='',encoding='utf8') as file:
# 写入文件类
fw = csv.writer(file)
fw.writerow(["abcdefgh",'username'])
fw.writerow(['helloworld','xiaoming'])
fw.writerows([('hahaha','wawawa'),('xiaoming','xiaowang')])
# dict字典方式写入
with open('./data.csv',mode='w',newline='',encoding='utf8') as file:
field_names = ['username','passwd']
cdw = csv.DictWriter(file,fieldnames=field_names) # 制定表头
cdw.writeheader() # 写入表头
cdw.writerow({'username':'xiaoming','passwd':'123456'})
cdw.writerow({'username': 'xiaowang', 'passwd': '123456'})
# 读取csv文件
with open('./data.csv',mode='r',newline='',encoding='utf8') as file:
cr = csv.reader(file)
for line in cr:
print(line)
ini文件处理-ConfigParser
写入
import configparser
#实例化对象
config = configparser.ConfigParser()
config['Default'] = {
"IP":"127.0.0.1",
"port":3000,
"user":"root",
"passwd":123456
}
config['uat'] = {
"IP": "192.168.1.101",
"port": 3000,
"user": "root",
"passwd": 123456
}
with open('./config.ini',mode='w',encoding='utf8') as file:
config.write(file)
读取
#实例化对象
config = configparser.ConfigParser()
config.read('./config.ini')
print(config.sections())
test_data = {}
for section in config.sections():
print(section,config[section])
test_data[section] = {}
for key in config[section]:
test_data[section][key] = config[section][key]
print(key,config[section].get(key))
print(test_data)
yaml文件处理
import yaml
# 解析数据
data = """
- Cat
- Dog
- Goldfish
"""
print(yaml.safe_load(data)) # ['Cat', 'Dog', 'Goldfish'] import yaml
data = {
"name":'xiaoming',
'age':20
}
# 写入文件
data = {
'data':[1,2,3,4,5],
"name":'xiaoming',
'age':20
}
with open('./data.yaml',mode='w',encoding='utf8') as file:
yaml.safe_dump(data,file)
# 读取文件
with open('./data.yaml',mode='r',encoding='utf8') as file:
print(yaml.safe_load(file))
邮件处理
# !/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 第三方 SMTP 服务
# 邮箱服务器地址
mail_host = "smtp.163.com"
# 用户名
mail_user = "*********@163.com"
# 密码(部分邮箱为授权码)
mail_pass = "*******"
#邮件发送方邮箱地址
sender = '****@163.com'
# 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receivers = ['*******@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 设置三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('今天天气很好,我想邀你一起出去吃饭!', 'plain', 'utf-8')
# 发送方信息 此处格式:<邮箱地址>,否则会被当做垃圾邮件处理,接收不到
message['From'] = '<*********@163.com>'
# 接收方信息
message['To'] = '<*******@qq.com>'
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP()
# smtpObj = smtplib.SMTP_SSL(mail_host)
# 连接到服务器 25 为 SMTP 端口号
smtpObj.connect(mail_host, 25)
# 登录邮箱
smtpObj.login(mail_user, mail_pass)
print(smtpObj)
# 发送邮件
smtpObj.sendmail(sender, receivers, message.as_string())
# 退出
smtpObj.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件" )
发送附件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 邮箱服务器地址
mail_host = "smtp.163.com"
# 用户名
mail_user = "**********@163.com"
# 密码(部分邮箱为授权码)
mail_pass = "**********"
sender = '**********@163.com'
receiver = ['**********@163.com','********@qq.com']
# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = '<**********@163.com>'
message['To'] = '<********@qq.com>'
subject = 'Python SMTP测试'
message['subject'] = Header(subject,'utf-8')
# 邮件正文的内容
message.attach(MIMEText('快到元旦了!','plain','utf-8'))
# 构造附件1,传送当前目录下的文件
att1 = MIMEText(open('test12082021','rb').read(),'base64','utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的file可以任意写,展示在邮件中
att1["Content-Disposition"] = 'attachment;filename="test.txt"'
message.attach(att1)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender,receiver,message.as_string())
print("发送成功!!!")
except smtplib.SMTPException:
print("Error:发送邮件失败!!!")
发送带图片的邮件
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
# 第三方 SMTP 服务
# 邮箱服务器地址
mail_host = "smtp.163.com"
# 用户名
mail_user = "a18179641565@163.com"
# 密码(部分邮箱为授权码)
mail_pass = "QPIPVLIUATBFBSCE"
#邮件发送方邮箱地址
sender = 'a18179641565@163.com'
# 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
receivers = ['yaxin.liang@melot.cn'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
message = MIMEMultipart('related')
# 发送方信息 此处格式:<邮箱地址>,否则会被当做垃圾邮件处理,接收不到
message['From'] = '<a18179641565@163.com>'
# 接收方信息
message['To'] = '<yaxin.liang@melot.cn>'
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative')
message.attach(msgAlternative)
mail_msg = """
<p> 邮件发送</p>
<p><a href = "http://www.baidu.com">百度链接</a></p>
<p>家居卧室图片</p>
<p><img src = "cid:img.png"></p>
"""
msgAlternative.attach(MIMEText(mail_msg,'html','utf-8'))
# 指定图片为当前目录 读取图片
fp = open('img.png','rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定义图片ID,在HTML文本中引用
msgImage.add_header('Content-ID','<img>')
message.attach(msgImage)
try:
smtpObj = smtplib.SMTP()
# smtpObj = smtplib.SMTP_SSL(mail_host)
# 连接到服务器 25 为 SMTP 端口号
smtpObj.connect(mail_host, 25)
# 登录邮箱
smtpObj.login(mail_user, mail_pass)
# 发送邮件
smtpObj.sendmail(sender, receivers, message.as_string())
# 退出
smtpObj.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件" )
使用yagmail发送邮件:
import yagmail
MAIL_HOST='smtp.163.com'
MAIL_USER='a1817964***@163.com'
# 此处的密码是指163.com的授权码
MAIL_PASSWRD = '授权码'
TO = [******1507@qq.com'
]
title = 'test'
content = 'hahahha'
def sendmail(title,content,attrs=None):
try:
# 当是qq邮箱时,需加入smtp_ssl=True
m = yagmail.SMTP(host=MAIL_HOST,user=MAIL_USER
,password=MAIL_PASSWRD,smtp_ssl=True
)
m.send(to=TO,subject=title,
contents=content,
attachments=attrs)
print('发送邮件完成')
except Exception as e:
print(e)
sendmail(title,content)
对象
# 类对象相当于是调用了_new_方法,实例对象相当于是调用了_init_方法
class Person(object):
def __new__(cls, *args, **kwargs):
print('__new__被调用执行了,cls的id值为{0}'.format(id(cls)))
obj = super().__new__(cls)
print('创建的对象的id为{0}'.format(id(obj)))
return obj
def __init__(self,name,age):
print('__init__被调用了,self的id值为{0}'.format(id(self)))
self.name = name
self.age = age
print('object这个类对象的id为:{0}'.format(id(object)))
print('Person这个类对象的id为:{0}'.format(id(Person)))
# 创建person类的实例对象
p1 = Person('张三',20)
print('p1这个Person类的实例变量对象的id:{0}'.format(id(p1)))
结果
E:\Python\Python37\python.exe D:/Workspace/projects/pythonStudy/chap12/demo6.py
object这个类对象的id为:140715263895584
Person这个类对象的id为:2426911731160
__new__被调用执行了,cls的id值为2426911731160
创建的对象的id为2426949861640
__init__被调用了,self的id值为2426949861640
p1这个Person类的实例变量对象的id:2426949861640
Process finished with exit code 0
继承 重写 常见特殊方法、特殊属性
# 下划线
# __foo__ : 双下划线 定义的特殊方法,一般是系统名字,如__init__
# _foo : 单下划线 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *
# __foo : 双下划线 表示的是私有类型(private)的变量, 只允许这个类本身进行访问
# 普通方法和类方法的区别在于,是否带参数self self是实例 表示当前对象的地址
# 类的私有方法/私有属性 调用,必须使用 self.__private_methods
# 子类中需要父类的构造方法就需要显式地调用父类的构造方法,或者不重写父类的构造方法
class Person(object):
# 构造函数/初始化函数 实例必调用
def __init__(self,name,age):
self.name = name
self.age = age
def info(self):
print(self.name,self.age)
class Student(Person):
def __init__(self,name,age,stu_no):
# 使用super()调用父类的构造方法
super().__init__(name,age)
self.stu_no = stu_no
# 方法重写
def info(self):
# 调用父类的方法
super().info()
print(self.stu_no)
class Teacher(Person):
def __init__(self,name,age,teachofyear):
super().__init__(name,age)
self.teachoyear = teachofyear
def info(self):
super().info()
print('教龄',self.teachoyear)
stu = Student('张三',20,'1001')
teacher = Teacher('李四',30,10)
stu.info()
teacher.info()
print('---------------------------多继承------------------------')
class A():
pass
class B():
pass
class C(A,B):
def __init__(self,name,age):
self.name = name
self.age = age
x = C('Jack',20)
print(x.__dict__) #实例对象的属性字典
print(x.__class__) #输出了对象所属的类
print(C.__bases__) #C类的父类类型元素
print(C.__base__) #离自己最近的父类(基类)
print(C.__mro__) #类的层次结构
print(A.__subclasses__()) #A的子类的列表
私有变量
class Student:
def __init__(self,name,age):
self.name = name
# 私有变量使用__变量名,私有变量不能在类的外部使用 不能被实例访问 内部使用self.private_methods调用
self.__age = age
def show(self):
print(self.name,self.__age)
stu1 = Student('张三',20)
stu1.show()
# 在类的外部使用name,age
print(stu1.name)
# 报错,不能调用私有变量
# print(stu1.__age)
print(dir(stu1))
print(stu1._Student__age) #在类的外部可以通过 _Student__age进行访问
静态变量
def varfunc():
# var 普通方法中的普通变量
var = 0
print ('var = %d' % var)
var += 1
if __name__ == '__main__':
for i in range(3):
varfunc()
# 类的属性
# 作为类的一个属性吧
class Static:
# StaticVar 类中的静态变量 值会根据对象的调用而变化
StaticVar = 5
def varfunc(self):
self.StaticVar += 1
print (self.StaticVar)
print (Static.StaticVar)
a = Static()
for i in range(3):
a.varfunc()
重写
a = 20
b = 100
c = a + b
d = a.__add__(b)
print(c)
print(d)
class Student:
def __init__(self,name):
self.name = name
def __add__(self, other):
return self.name + other.name
def __len__(self):
return len(self.name)
stu1 = Student('Jack')
stu2 = Student('李四')
# 实现了两个对象的加法运算(因为在Student类中 编写了__add__()的特殊方法)
s = stu1 + stu2
print(s)
s = stu1.__add__(stu2)
print(s)
print('---------------------------------------------')
lst = [11,22,33,44]
print(len(lst))
print(lst.__len__())
print(len(stu1))
静态方法 实例方法 类方法 函数 类属性 实例属性 动态绑定属性、方法
class Student:
native_pace = '吉林' #直接写在类里的变量,称为类属性
def __init__(self,name,age):
#实例属性,将局部变量name赋值给实例变量
self.name = name
self.age = age
#实例方法
def eat(self):
print('学生在吃饭。。。')
#静态方法 方法中不能使用self
@staticmethod
def method():
print('我使用了staticmethod进行修饰,所以我是静态方法')
#类方法
@classmethod
def cm(cls):
print('我是类方法,因为我使用了classmethod进行修饰,所以我是静态方法')
#在类之外定义的称为函数,在类之内定义的称为方法
def drink():
print("喝水")
# 创建Student类对象
stu1 = Student('张三',20)
print(id(stu1))
print(type(stu1))
print(stu1)
print(id(Student))
print(type(Student))
print(Student)
stu1.eat()
print(stu1.name)
print(stu1.age)
print('...................')
Student.eat(stu1) #33行和28行,都是调用Student中的eat方法
# 类属性的使用方法
print(Student.native_pace)
stu2 = Student('李四',30)
print(stu1.native_pace)
print(stu2.native_pace)
Student.native_pace = '天津'
print(stu1.native_pace)
print(stu2.native_pace)
print("--------------类方法的使用方式--------------")
Student.cm()
print("--------------静态方法的使用方式-------------")
Student.method()
print("--------------动态绑定属性-------------------")
stu2.gender = '女'
print(stu2.name,stu2.age,stu2.gender)
print("------------动态绑定方法---------------------")
def show():
print('定义在类之外的函数')
stu1.show = show()
stu1.show()
一些第三方库的使用
# 获取与python解释器及其环境相关的标准库
import sys
# 提供与时间相关的各种函数的标准库
import time
# 提供了访问操作系统服务功能的标准库
import os
# 提供与日期相关的各种函数的标准库
import calendar
# 用于读取来自网上(服务器)的数据标准库
from urllib import request
# 用于使用json序列化和反序列化对象
import json
# 用于在字符串中执行正则表达式匹配和替换
import re
# 提供标准算术运算函数的标准库
import math
# 用于进行精准控制运算精度、有效数位、四舍五入的十进制运算
import decimal
# 提供了灵活的记录事件、错误、警告和调试信息等日志信息的功能
import logging
import random
print(random.randint(1,100))
print(sys.getsizeof(24))
print(sys.getsizeof(45))
print(sys.getsizeof(True))
print(sys.getsizeof(False))
print(time.time())
print(time.localtime(time.time()))
print(time.strftime("%y-%m-%d %H:%M:%S"))
print(request.urlopen('http://www.baidu.com').read())
print(math.pi)
拷贝
# 拷贝
class CPU:
pass
class Disk:
pass
class Computer:
def __init__(self,cpu,disk):
self.cpu = cpu
self.disk = disk
# 赋值 cpu1和cpu2的实例变量值一样,指向的是同一个对象
cpu1 = CPU()
cpu2 = cpu1
print(cpu1,id(cpu1))
print(cpu2,id(cpu2))
disk = Disk()
computer = Computer(cpu1,disk)
print('.................................')
#浅拷贝 只复制对象,不复制对象包含的子对象内容 源对象与拷贝对象会引用同一个子对象
import copy
computer2 = copy.copy(computer)
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)
print('..................................')
#深拷贝 递归拷贝对象中包含的子对象,源对象和拷贝对象所有子对象不相同
computer3 = copy.deepcopy(computer)
print(computer,computer.cpu,computer.disk)
print(computer3,computer3.cpu,computer3.disk)
Python GUI编程(Tkinter)
# TKinter Python的标准GUI库,可快速创建本地应用程序,创建本地窗口风格
# 创建一个GUI程序的步骤:
# 1、导入Tkinter模块
# 2、创建控件
# 3、指定这个控件的master,即这个控件属于哪一个
# 4、告诉GM(geometry manager)有一个控件产生了
# eg1:
import tkinter
root = tkinter.Tk() # 创建窗口对象的背景颜色
li = ['C','python','php','html','SQL','java'] # 创建两个列表
movie = ['CSS','jQuery','Bootstrap']
listb = tkinter.Listbox(root) # 创建两个列表组件
listb2 = tkinter.Listbox(root)
for i in li:
listb.insert(0,i)
for i in movie:
listb2.insert(0,i)
listb.pack() # 将小部件放置到主窗口中
listb2.pack()
root.mainloop() # 进入消息循环
# eg2:
from tkinter import *
import hashlib
import time
LOG_LINE_NUM = 0
class MY_GUI():
def __init__(self,init_window_name):
self.init_window_name = init_window_name
#设置窗口
def set_init_window(self):
self.init_window_name.title("文本处理工具_v1.2") #窗口名
#self.init_window_name.geometry('320x160+10+10') #290 160为窗口大小,+10 +10 定义窗口弹出时在屏幕上的默认展示位置
self.init_window_name.geometry('1068x681+10+10')
# self.init_window_name["bg"] = "pink" #窗口背景色,其他背景色见:blog.csdn.net/chl0000/article/details/7657887
#self.init_window_name.attributes("-alpha",0.9) #虚化,值越小虚化程度越高
#标签
self.init_data_label = Label(self.init_window_name, text="待处理数据")
self.init_data_label.grid(row=0, column=0)
self.result_data_label = Label(self.init_window_name, text="输出结果")
self.result_data_label.grid(row=0, column=12)
self.log_label = Label(self.init_window_name, text="日志")
self.log_label.grid(row=12, column=0)
#文本框
self.init_data_Text = Text(self.init_window_name, width=67, height=35) #原始数据录入框
self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10)
self.result_data_Text = Text(self.init_window_name, width=70, height=49) #处理结果展示
self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
self.log_data_Text = Text(self.init_window_name, width=66, height=9) # 日志框
self.log_data_Text.grid(row=13, column=0, columnspan=10)
#按钮
self.str_trans_to_md5_button = Button(self.init_window_name, text="字符串转MD5", bg="lightblue", width=10,command=self.str_trans_to_md5) # 调用内部方法 加()为直接调用
self.str_trans_to_md5_button.grid(row=1, column=11)
#功能函数
def str_trans_to_md5(self):
src = self.init_data_Text.get(1.0,END).strip().replace("\n","").encode()
#print("src =",src)
if src:
try:
myMd5 = hashlib.md5()
myMd5.update(src)
myMd5_Digest = myMd5.hexdigest()
#print(myMd5_Digest)
#输出到界面
self.result_data_Text.delete(1.0,END)
self.result_data_Text.insert(1.0,myMd5_Digest)
self.write_log_to_Text("INFO:str_trans_to_md5 success")
except:
self.result_data_Text.delete(1.0,END)
self.result_data_Text.insert(1.0,"字符串转MD5失败")
else:
self.write_log_to_Text("ERROR:str_trans_to_md5 failed")
#获取当前时间
def get_current_time(self):
current_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
return current_time
#日志动态打印
def write_log_to_Text(self,logmsg):
global LOG_LINE_NUM
current_time = self.get_current_time()
logmsg_in = str(current_time) +" " + str(logmsg) + "\n" #换行
if LOG_LINE_NUM <= 7:
self.log_data_Text.insert(END, logmsg_in)
LOG_LINE_NUM = LOG_LINE_NUM + 1
else:
self.log_data_Text.delete(1.0,2.0)
self.log_data_Text.insert(END, logmsg_in)
def gui_start():
init_window = Tk() #实例化出一个父窗口
ZMJ_PORTAL = MY_GUI(init_window)
# 设置根窗口默认属性
ZMJ_PORTAL.set_init_window()
init_window.mainloop() #父窗口进入事件循环,可以理解为保持窗口运行,否则界面不展示
gui_start()
python 操作PostgreSql数据库
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
fetchall():接收全部的返回结果行.
rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数
--------postgresql-------
import psycopg2
# 连接到一个指定的数据库 如果是mysql数据库,则导入pymysql,使用pymysql.connect()连接
conn = psycopg2.connect(database = "***",user ="***",password="***",host="****",port="****")
# 建立游标,用来执行数据库操作
cursor = conn.cursor()
# 执行SQL命令 为了防止SQL注入,采用%s数据类型
sql = "select * from melotpay.agency_info where userno in (%s,%s,%s)"
data = ('22023','22024','596490070')
try:
cursor.execute(sql,data)
# 获取SELECT返回的元组
# 如果只使用查询语句不用commit方法,insert/update/delete等操作需要调用commit()
# conn.commit()
rows = cursor.fetchall()
for row in rows:
print('id = ',row[0],'name = ',row[1],'\n')
except:
# 发生错误进行回滚到上次调用commit()方法之后,一般用在insert/update/delete等操作
conn.rollback()
finally:
# 关闭游标
cursor.close()
# 关闭数据库
conn.close()
urllib库
https://www.runoob.com/python3/python-urllib.html
import urllib.request
from urllib.request import urlopen
import urllib.error
# ===================================== urllib.request ======================================
# urllib.request---打开和读取 URL
# urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
myURL = urlopen("https://www.runoob.com/")
# 读取整个网页内容
print(myURL.read())
# 指定读取长度
print(myURL.read(300))
# 读取文件的一行内容
print(myURL.readline())
# 读取文件的全部内容,并将获取的内容赋值给列表
lines = myURL.readlines()
for line in lines:
print(line)
# 获取网页状态码
myURL01 = urllib.request.urlopen("https://www.runoob.com/")
print(myURL01.getcode())
# URL编码与解码
encode_url= urllib.request.quote("https://www.runoob.com")
print(encode_url)
# # 解码
unencode_url = urllib.request.unquote(encode_url)
print(unencode_url)
# 对 headers(网页头信息)进行模拟,发送请求
# 提交到表单页面
url = 'https://www.runoob.com/try/py3/py3_urllib_test.php'
# 提交数据
data = {'name':'RUNOOB', 'tag' : '菜鸟教程'}
# 头部信息
header = {
'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
# 对参数进行编码,解码使用 urllib.parse.urldecode
data = urllib.parse.urlencode(data).encode('utf8')
# 请求处理
request=urllib.request.Request(url, data, header)
response = urllib.request.urlopen(request)
print(response.code)
# ===================================== urllib.error ======================================
# urllib.error---包含 urllib.request 抛出的异常
myURL2 = urllib.request.urlopen("https://www.runoob.com/")
print(myURL2.getcode())
try:
myURL3 = urllib.request.urlopen("https://www.runoob.com/no.html")
except urllib.error.HTTPError as e:
print('code:'+str(e.code))
print('reason:'+str(e.reason))
print('=====headers:====')
print(str(e.headers))
if e.code == 404:
print(404)
# ===================================== urllib.parser ======================================
# urllib.parser---解析 URL
# urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)
# 解析后:ParseResult(scheme='https', netloc='www.runoob.com', path='/', params='', query='s=python+%E6%95%99%E7%A8%8B', fragment='')
o = urlparse("https://www.runoob.com/?s=python+%E6%95%99%E7%A8%8B")
print(o)
# ===================================== urllib.robotparser ======================================
# urllib.robotparser--解析 robots.txt 文件