1.python中条件判断语句:if-elif-else
**python中没有:switch..case语句
a,b=7,-1 print('----------------------') while a!=b: x = int(input("请输入一个数字:")) if x == a: print('输入正确!') elif x > a: print('太大!') elif x < a: print('太小!')
2.for循环、while循环
①for循环
#for循环常用于遍历序列 #结合range()+len()遍历序列的索引 x=["a","b","c","d"] for i in range(len(x)): print(i,x[i]) >>> 0 a 1 b 2 c 3 d @for中嵌套if for i in range(2,10): for x in range(2,i): if i % x == 0: print(i,'等于',x,'*',i//x) break else: #循环中没有找到元素 print(i,'是质数') >>> 2 是质数 3 是质数 4 等于 2 * 2 5 是质数 6 等于 2 * 3 7 是质数 8 等于 2 * 4 9 等于 3 * 3 @for循环使用'else'、'break'、'continue' sites = ["Baidu", "Google","Runoob","Taobao","JD","yahu","tenxun"] for i in sites: if i == "Google": print("跳过循环") continue elif i == "JD": print('停止循环!') break print("循环的数据:" + i) else: print("没有循环的数据!") print("完成循环")
②while循环
**python中没有do..while()循环
#while循环 n,sum,count = 100,0,1 while count <= n: sum = sum + count count += 1 print('1到%d的和为:%d' % (n,sum)) >>>1到100的和为:5050 @while循环中'else'的使用,在语句为false时执行else语句 count = 0 while count < 5: print(count,'< 5') count = count + 1 else: print(count,'>= 5') >>> 0 < 5 1 < 5 2 < 5 3 < 5 4 < 5 5 >= 5 @break和continue语句 i = 10 while i > 0: i = i - 1 if i == 5: continue elif i == 3: break print('输出:%s' % i) print('GODD BYE !')
3.列表、元组、字典、集合
①列表
#1.列表 list=[0,1,2,3,4] @截取:下标,print(list[2:]) @更新:下标,list[2]=9 @删除:下标,del list[2] @长度:print(len(list)) @集合拼接:list+list2; list+=[2,3,4,4,5,6] print(list) @函数: #len(list) 列表长度 #max(list) 返回列表元素最大值 #min(list) 返回列表元素最小值 #list(seq) 将元组转换为列表 #for x in [1, 2, 3]: print(x, end=" ") 迭代输出 @方法: ①.list.addend(5) 在列表末尾追加5 x = [1,2,3,2,2,2,] x.append(5) print(x) 在末端添加多个元素: breakfast.extend(["juice","decaf","tom","tea","egg"]) print(breakfast) ②.list.count(4) 统计4元素在列表出现的次数 x = [1,2,3,2,2,2,] s=x.count(2) print(s) >>>4 ③.list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) x = [1,2,3,2,2,2,] x.extend([3,4,5]) print(x) >>>[1, 2, 3, 2, 2, 2, 3, 4, 5] ④.list.index(obj) 从列表中找出某个值第一个匹配到的索引位置 x = [1,2,3,2,2,2,] s=x.index(3) print('对应的下标位置:',s) >>>对应的下标位置: 2 ⑤.list.insert(index,obj) 根据下标增加元素 **如果指定的下标有元素,insert作为更新使用 x = [1,2,3,4,5,6] x.insert(4,7) print(x) >>>[1,2,3,4,7,6] ⑥.list.pop() 随机删除列表中的元素并返回该元素,默认是最后一个 x = [1,2,3,4,5,6] s=x.pop() print(s) >>>6 ⑦.list.remove() 指定删除列表元素 x = [1,2,3,4,5,6] x.remove(4) print(x) >>>[1,2,3,5,6] ⑧.list.reverse() 反转列表中的元素 x = [1,2,3,4,5,6] x.reverse() print(x) >>>[6, 5, 4, 3, 2, 1] ⑨.list.sort() 对原列表进行排序 x = [1,6,7,3,2,5] x.sort() print(x) >>>[1, 2, 3, 5, 6, 7] ⑩.list.clear() 清空列表 x = [1,2,3,2,2,2,] x.clear() print(x) >>>[] 十一.list,.copy() 复制列表 x = [1,6,7,3,2,5] s= x.copy() s+=[11,9] print(s) >>>[1, 6, 7, 3, 2, 5, 11, 9]
**列表中常用的数据结构方法***
#①嵌套列表解析:将3x4的矩阵列表转换为4x3列表 matrix = [1,2,3,4],[5,6,7,8],[9,10,11,12] transposed = [] for i in range(4): transposed.append([row[i] for row in matrix]) print(transposed ) >>>[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #以上方法等同于: x = [[row[i] for row in matrix] for i in range(4)] print(x) >>>[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #② o = [2,4,6] s=[[i,i*3] for i in o] print(s) >>>[[2, 6], [4, 12], [6, 18]] #③ o = [2,4,6] x = [3*i for i in o if i>3] print(x) >>>[12, 18] #④ v1 = [1,2,3,4] v2 = [5,6,7,8] s = [x*y for x in v1 for y in v2] print(s) >>>[5, 6, 7, 8, 10, 12, 14, 16, 15, 18, 21, 24, 20, 24, 28, 32] l = [v1[i]*v2[i] for i in range(len(v1))] print(l) >>>[5, 12, 21, 32]
②元组
#2.tup=() #元组中的元素不允许修改,可截取,拼接 @创建:tup=(50,)(元组中只包含一个元素时,需要在元素最后添加逗号,否则括号会被当作运算符来使用) @截取:下标,print(tulp[1]) @拼接:tup3=t1+t2 @删除:del tup(元组中的元素不允许删除,正能删除整个元组) @迭代:for x in (1,2,3): print(x,end=' ') >>>123 #函数 ①.len(tuple) 计算元组的元素个数 tup=(1,2,3,4) print(len(tup)) >>>4 ②.max(tuple) 返回元组中元素最大值 ③min(tuple) 返回元组中元素最小值 ④.tuple(seq) 将列表转换为元组 x=[0,2,3,4] print(tuple(x)) >>>(0, 2, 3, 4)
③字典
#dict={key1:value1,key2:value2},key值唯一不可变,value可 #字典键的特性:字典值-可以是任何python对象,既可以是标准对象,也可以是用户自定义;键是唯一不可变的,如果相同的字典中出现了相同的键,那么相同的键只会输出最后一次赋的值,键不可用列表 @创建:dict = {'abc':456,5:9} @访问:通过键,print(dict['abc']) @更新:通过键,dict['abc'] = 8 @添加:键值对,dict['School'] = "测试添加" @删除:del dict['abc'] 删除键 del.clear() 清空字典 del dict 删除字典 #函数 ①.len(dict) 字典的键值对个数 dict = {'abc':123,'tom':3,5:7} print(len(dict)) >>>3 ②str(dict) 输出字典 dict = {'abc':123,'tom':4,'jon'"7} print(str(dict)) >>>{'abc':123,'tom':4,'jon'"7} #方法 ①dict.clear() 删除字典内所有元素 x = {'abc':123,4:5,7:8} x.clear() print(x) >>>{} ②dict.copy() 浅拷贝一个字段 #dict1=dict.copy() 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用; #dict1 = dict 浅拷贝: 引用对象 x = {'abc':123,4:5,7:8} s = x.copy() print(s) >>>{'abc':123,4:5,7:8} ③dict.fromkeys(seq) 创建一个新的字典 #将列表转换为字典 seq=('name','age','sex') dict = dict.fromkeys(seq) #返回空值的键 print("新的字典:%s" % str(dict)) >>>新的字典:{'name': None, 'age': None, 'sex': None} **** seq=('name','age','sex') dict = dict.fromkeys(seq,10) #返回赋值的键 s=dict['name']='tom' #更新值 print("新的字典:%s" % str(dict)) print('新的dict:'dict) #赋值返回新的dict >>>新的字典:{'name': 'tom', 'age': 10, 'sex': 10} ④dict.get(key) 返回指定键的值 dict = {'key1': 2, 'key2': None, 'key3': None} print(dict.get('key1')) >>>2 ⑤key in dict 判断键是否在dict中 ⑥dict.items() 以列表返回可遍历的(键,值)元组数组 dict = {'key1': 2, 'key2': 4, 'key3': 5} print(dict.items()) >>>dict_items([('key1', 2), ('key2', 4), ('key3', 5)]) ⑦dict.keys() 返回一个迭代器,可以用你list()来转换为列表 dict = {'key1': 2, 'key2': 4, 'key3': 5} print(list(dict.keys())) >>>['key1', 'key2', 'key3'] #只返回键 ⑧dict.setdefault(key,defualt=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default dict = {'key1': 2, 'key2': 4, 'key3': 5} print('查询的键:%s' % dict.setdefault('key4')) #查找的键 print('返回新的字典:%s' % dict) #返回新添加的键值对 >>>查询的键:None >>>返回新的字典:{'key1': 2, 'key2': 4, 'key3': 5, 'key4': None} ⑨dict.update(dict2) 把字典dict2的键值对更新到dict中 dict = {'key1': 2, 'key2': 4, 'key3': 5} dict2 = {'key6': 7,} dict.update(dict2) print(dict) >>>{'key1': 2, 'key2': 4, 'key3': 5, 'key6': 7} ⑩dict.values() 返回一个迭代器,可以用list()来转换为列表 dict = {'key1': 2, 'key2': 4, 'key3': 5} print(list(dict.values())) >>>[2, 4, 5] #同keys相反,values()只取返回值 ⑾dict.pop(key) 删除字典给定的键key所对应的值并返回 dict = {'key1': 2, 'key2': 4, 'key3': 5} print(dict.pop('key1')) print(dict) >>>2 >>>{'key2': 4, 'key3': 5} ⑿dict.popitem() 随机删除字典中的一对和值(一般删除最后一对) dict = {'key1': 2, 'key2': 4, 'ksey3': 5} print(dict.popitem()) print(dict) >>>('ksey3', 5) >>>{'key1': 2, 'key2': 4}
④集合
#集合 set={value} 或 set=(value),创建空的集合:set=() ,{} 为创建空的字典 #集合是一个无序的不重复的元素序列 @创建:set(value) @去重:a = {'name','age','sex','sex','name','age'} print(a)>>>{'name','age','sex'} @运算: ①集合a内包含不包含集合b的元素:a-b a={'abcdef'} b={'abrt'} print(a-b) >>>{'abcdef'} ②集合a或b中包含的所有元素:a|b a={'abcdef'} b={'abrt'} print(a|b) >>>{'abcdef', 'abrt'} ③集合a和b都包含的元素:a&b a={'abcdef','tom'} b={'abrt','tom'} print(a&b) >>>{'tom'} ④不同时包含于a和b的元素:a^b a={'abcdef','tom'} b={'abrt','tom'} print(a^b) >>>{'abrt', 'abcdef'} #方法 ①add() 为集合添加元素 a={'abcdef','tom'} a.add('jir') a.add('erer') print(a) >>>{'jir', 'tom', 'abcdef', 'erer'} ②clear() 移除集合中的所有元素 b={'abrt','tom'} b.clear() print(b) >>>set() ③copy() 拷贝一个集合 b={'abrt','tom'} x=b.copy() print(x) >>>{'abrt', 'tom'} ④difference() 返回多个集合的差集,返回一个新的set() x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} z = x.difference(y) #以X作为参数,y进行匹配 print(z) >>>{'banana', 'cherry'} ⑤set.difference_update() 在原来的集合上移除重复的数据,不反回新的set() x = {"apple", "banana", "cherry"} y = {"google", "microsoft", "apple"} x.difference(y) #以X作为参数,y进行匹配,最后结果返回x print(x) >>>{'banana', 'cherry'} ⑥set.discard(value) 删除集合中指定的元素 a = {"apple", "banana", "cherry"} a.discard('apple') print(a) >>> {'cherry', 'banana'} ⑦set.intersection() 返回集合的交集 a = {"apple", "banana", "cherry"} b = {"apple", "banana","erer","ertrt"} s=a.intersection(b) print(s) >>>{'apple', 'banana'} ⑧set.intersection_update() 删除集合中的元素,该元素在指定的集合中不存在 x = {"apple", "banana", "cherry"} y = {"google", "runoob", "apple"} x.intersection_update(y) print(x) >>>{'apple'} ⑨set.isdisjoint() 判断两个集合是否包含相同的元素,ture/false #判断集合 y 中是否有包含 集合 x 的元素 x = {"apple", "banana", "cherry"} y = {"google", "runoob", "facebook"} z = x.isdisjoint(y) print(z) #不包含返回true,反之false >>>true ⑩set.issubset() 判断指定集合是否为改方法参数集合的子集 #判断集合 x 的所有元素是否都包含在集合 y 中 x = {"a", "b", "c"} y = {"f", "e", "d", "c", "b", "a"} z = x.issubset(y) print(z) >>>true #集合y中包含了a集合的所有元素 ⑾set.issuperset() 判断该方法的参数集合是否为指定集合的子集 #判断集合 y 的所有元素是否都包含在集合 x 中 x = {"f", "e", "d", "c", "b", "a"} y = {"a", "b", "c"} z = x.issuperset(y) print(z) >>>true #a集合包含了y集合的所有元素 ⑿set.pop() 随机删除集合中的元素并返回删除的元素 x = {"apple", "banana", "cherry"} print(x.pop()) >>> ⒀set.remove() 移除指定集合中的元素 x = {"apple", "banana", "cherry"} x.remove('apple') print(x) >>>{'cherry', 'banana'} ⒁set.symmetric_difference() 返回两个集合中不重复的元素集合 x = {"apple", "banana", "cherry","tom"} y = {"google", "runoob", "apple","tom"} z = x.symmetric_difference(y) print(z) >>>{'runoob', 'google', 'banana', 'cherry'} ⒂set.symmetric_difference_update() 将两个集合合并并删除重复的值 #在原始集合 x 中移除与 y 集合中的重复元素,并将不重复的元素插入到集合 x 中 x = {"apple", "banana", "cherry"} y = {"google", "runoob", "apple"} x.symmetric_difference_update(y) print(x) >>>{'runoob', 'cherry', 'google', 'banana'} ⒃set.union() 返回两个集合的并集 #将两个集合合并并过滤掉忽略重复的元素 x = {"apple", "banana", "cherry"} y = {"google", "runoob", "apple"} z = x.union(y) print(z) >>>{'cherry', 'runoob', 'google', 'apple', 'banana'} ⒄set.update() 给集合添加元素 #添加元素: x = {"apple", "banana", "cherry"} y = {"google", "runoob", "apple"} x.update({"tom"}) print(x) >>>{'tom', 'cherry', 'apple', 'banana'} #添加集合元素:组合两个集合并忽略重复的元素 x = {"apple", "banana", "cherry"} y = {"google", "runoob", "apple"} x.update(y) print(x) >>>{'google', 'banana', 'runoob', 'cherry', 'apple'}
4.迭代器与生成器
@迭代器 可创建的对象;字符串、列表、元组 @基本方法:iter()和next() @创建: x = [1,2,3,4,5] s = iter(x) >>>print(next(s)) #next()方法逐个打印 >>>print(next(s)) @for循环进行遍历打印: x = [1,2,3,4,5] s = iter(x) for i in s: print(i,end=' ') >>>1 2 3 4 5 @next()方法循环输出: import sys x = [1,2,3,4,5] it = iter(x) while True: try: print(next(it),end=' ') except StopIteration: sys.exit() >>>1 2 3 4 5 #生成器 :yield函数 生成器=迭代器 import sys def yield_new(n): #生成器函数 - 斐波那契 a,b,c = 0,1,0 while True: if c > n: return yield a a,b = b,a + b c += 1 s = yield_new(10) # s 迭代器 由生成器返回生成 while True: try: print(next(s),end=" ") except StopIteration: sys.exit()
5.函数
①默认参数
def printinfo(name,age=18): print("姓名:%s" % name,end = ' ') print("年龄:%s" % age) return printinfo(name="tom",age=40) printinfo(name="root") >>> 姓名:tom 年龄:40 姓名:root 年龄:18
②不定长参数:加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。
#①不定长参数,声明时不会命名,语法: def functionname([formal_args,] *var_args_tuple ): "函数_文档字符串" function_suite return [expression] #②*号参数 def printinfo(arg1,*vartuple ): '打印传入的任何参数' print("输出:") print(arg1) print(vartuple) printinfo(70,80,60,50,"tom") >>> 输出: 70 (80, 60, 50, 'tom')
③两个**基本语法:
#语法: def functionname([forname_args,] **var_args_dict ): "函数_文档字符串" function_siuite return [expression] #加了两个**的参数会以字典的形式导入 def printinfo(arg1, **vardict ): print('输出:') print(arg1) print(vardict) printinfo(1,a=2,b=3) >>> 输出: 1 {'a': 2, 'b': 3} # *在参数中单独出现 def f(a,b,*,c): return a+b+c @*号单独出现,*后面的参数必须用关键字传入 def f(a,b,*,c): print(a+b+c) return f(1,2,c=3) >>>6
④.匿名函数
#匿名函数:lambda[arg1 [,arg2,........argn]]:expression sum = lambda arg1,arg2:arg1+arg2 print('sum:',sum(10,20)) >>>sum: 30
6.变量作用域
①作用域
# L(local) 局部作用域、E(Enclosing) 闭包函数外、G(Global) 全局作用域、B(Built-in) 内置作用域(内置函数所在模块的范围) #查找规则:L->E->G->B x = 0 #全局变量 def login(): x = 1 #闭包函数外的函数中 def inlog(): x = 2 # 局部作用域 # 内置作用域:引入buitin import builtins print(dir(builtins))
②global 和 nonlocal关键字
#规则:内部作用域想修改外部作用域的变量时 @global 关键字修改无嵌套的变量 num = 1 def self_f(): global num # 修改num的值 print(num) num = 123 print(num) self_f() >>>1 >>>123 @nonlocal 关键字修改嵌套作用域中的变量 def out(): num = 10 def inner(): nonlocal num num = 20 print(num) #打印全局变量num inner() print(num) # 调用inner()方法 ,修改num值 out() >>>10 >>>20 @调用全局变量作为参数是需要指定参数 a = 10 def test(a): #不指定变量a报错 a = a + 1 print(a) test(a) >>> 11
7.遍历的技巧
#遍历字典:关键字和对应的值可以使用items()方法解读出来 k = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in k.items(): print(k, v) >>>gallahad the pure >>>robin the brave #遍历序列:索引位置和对应值可以使用enumerate()函数同时解读 t = ['tom','gool','rengd','red'] for i, v in enumerate(t): print(i,v) >>> 0 tom 1 gool 2 rengd 3 red @遍历两个+的序列:使用zip()组合 a = ['name', 'quest', 'favorite color'] b = ['lancelot', 'the holy grail', 'blue'] for i, v in zip(a,b): print(i,v) >>> name lancelot quest the holy grail favorite color blue @反向遍历序列:reversed()函数 for i in reversed(range(1,10)): print(i,end=' ') >>>9 8 7 6 5 4 3 2 1 @按顺序遍历一个序列:sorted()函数 k = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for i in sorted(set(k)): print(i,end=' ') >>>apple banana orange pear
8.装饰器
9.输入输出
#输出格式化 @format()和%: import math print('常亮PI的值近似为:{:.3f}'.format(math.pi)) print('常亮PI的值近似为:%s' % math.pi) print('常亮PI的值近似为:%5.3f' % math.pi) >>>常亮PI的值近似为:3.142 >>>常亮PI的值近似为:3.141592653589793 >>>常亮PI的值近似为:3.142 @表达式和print()函数 @将输出的值转换为字符串:可以使用str()和repr()函数 ①str() :函数返回一个用户易读的表达式。 ②repr():产生一个解释器易读的表达式。(repr()函数可以转移字符串中的特殊字符,参数可以是python的任何对象) s = 'howll \n' print(repr(s)) print(str(s)) >>>'howll \n' >>>howll x = 10 * 3.25 y = 200 * 200 s = 'x 的值为: ' + repr(x) + ', y 的值为:' + repr(y) + '...' print(s) >>>x 的值为: 32.5, y 的值为:40000... #输出平方与立方 for x in range(1,11): print(repr(x).rjust(2),repr(x*x).rjust(3),repr(x*x*x).rjust(4)) >>> 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 @rjust:将字符串靠右, 并在左边填充空格 @ ljust() 和 center():不写入任何数据,只返回新的字符串 @zfill():在数字的左边填充0(字符串) i = '11' print(i.zfill(3)) >>>011 #输出平方与立方等同于 for x in range(1,11): print('{0:2d},{1:3d},{2:4d}'.format(x,x*x,x*x*x)) #{0:2d} 表示第一个参数x的格式。0 代表x,:2d 表示两个宽度的10进制数显示。 #{1:3d} 表示第一个参数x*x的格式。1 代表x*x,:3d 表示三个宽度的10进制数显示。 #{2:4d} 表示第一个参数x*x*x的格式。2代表x*x*x,:4d 表示四个宽度的10进制数显示。 #':' :在':'后传入一个整数,可以保证该域至少有这么多的宽度。用于美化表格时很有用 table = {'google':1,'runoob':2,'taobao':3} for name,number in table.items(): print('{0:10} ==> {1:10d}'.format(name,number)) # : 后传入一个整数 #格式化:最简单的就是传入一个字典, 然后使用方括号 '[]' 来访问键值 table = {'google':1,'runoob':2,'taobao':3} print('google:{0[google]:d},runoob:{0[runoob]:d},taobao:{0[taobao]:d}'.format(table)) >>>google:1,runoob:2,taobao:3 @实现以上方法:** table = {'google':1,'runoob':2,'taobao':3} print('google:{google:d},runoob:{runoob:d},taobao:{taobao:d}'.format(**table)) >>>google:1,runoob:2,taobao:3
10.斐波那契(fibonacci)
def fib(n): # 定义到 n 的斐波那契数列 a, b = 0, 1 while b < n: print(b, end=' ') a, b = b, a+b print() fib(1000) if __name__ == '__main__': fib(100)
11.Python File
# r :打开文件,只读方式 import os with open("Test.txt","r") as f: for line in f: print(line) f.close() #r + :打开一个文件用于读写,指针默认文件开头 #rb+ :以二进制格式打开一个文件用于读写,指针放到文件开头 #w :打开一个文件进行写入内容,不存在则创建新文件,并从头开始进行重新编辑(即原有内容会被删除) #w+ :打开一个文件用于读写,不存在则创建新文件,并从头开始进行重新编辑(即原有内容会被删除) #a :打开一个文件用于追加内容,文件指针在末尾,不存在则创建 #a+:打开一个文件用于读写内容,存在文件打开时为追加模式,文件指针在末尾,不存在则创建 import os def rfile(scr): with open(scr,'r') as f: for line in f: print(line) f.close() return def wfile(scr): with open(scr,'a+') as f: f.write('测试循环追加写入') f.close() return if __name__=='__main__': scr='Test.txt' wfile(scr) rfile(scr)
①指针:seek()函数
# f.seek():改变指针在当前文件中的位置,可以使用f.seek(offset,from_what)函数 #from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾,例如: #seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符 #seek(x,1) : 表示从当前位置往后移动x个字符 #seek(-x,2):表示从文件的结尾往前移动x个字符 import os with open('Test.txt','r') as s: print(s.read()) s.seek(0) # 将指针移到文件开头重新打印 print(s.read()) s.close() #tell()函数:统计整个文件中的字符数 import os with open('Test.txt','r') as s: print(s.read()) print(s.tell()) s.close()
②pickle 模块:数据序列和反序列化
# 基本接口:能对file以读取的形式打开 x = pickle.load(file) pickle.dump(obj, file, [,protocol]) # 使用pickle模块将数据对象保存到文件 import pickle data1 = {'a': [1, 2.0, 3, 4+6j], 'b': ('string', u'Unicode string'), 'c': None} selfred_list = [1,2,3] selfred_list.append(selfred_list) output = open('data.pkl','wb') #.pkl 二进制存储格式 pickle.dump(data1,output) pickle.dump(data1,output,-1) print(output) output.close() #使用pickle模块从文件中重构python对象 import pprint,pickle pkl_file = open('data.pkl', 'rb') data1 = pickle.load(pkl_file) pprint.pprint(data1) #pprint模块:打印data.pkl pkl_file.close()
③.方法
# 语法: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) @file:必须,文件路劲 @mode:可选,文件打开方式 @buffering:设置缓冲 @encoding:格式,一般使用utf8 @errors:报错级别 @newline:区分换行符 @closefd:传入的file参数类型 # 方法: ①file.open(scr,mode):打开文件 ②file.close():关闭文件,打开文件操作后都需要执行close()方法进行关闭以释放资源 ③file.flush():刷新文件内部缓冲,将缓冲的数据立刻写入文件 names=['tom','Jerry','mike'] names=[name + '\n' for name in names] #推倒表达式 返回一个list+\n f=open('Test.txt','w',encoding='utf8') f.writelines(names) f.flush() #不关闭文件情况下 将缓存在内存中的数据映射到硬盘文本中 print(names) f.close() ④file.fileon():返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上 ⑤file.isatty():文件链接到一个终端设备返回true,反之false ⑥file.next():返回文件下一行 ⑦file.rend([size]):读取文件指定的字节数,未给值或者给到负数则读取所有 ⑧file.readline():默认读取第一行,包括\n字符 f = open('Test.txt','r') print(f.readline()) f.close() ⑨file.readliness():读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区 f = open('Test.txt','r') print(f.readlines()) f.close() ⑩file.truncate([size]):从文件的首行首字符开始截断,截断文件为 size 个字符,无 size 表示从当前位置截断;截断之后后面的所有字符被删除,其中 Widnows 系统下的换行代表2个字符大小。 ⑾file.write():将字符介入文件,返回的是写入的字符长度 ⑿file.writelines(sequence):向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符 names=['tom','Jerry','mike'] f=open('Test.txt','w',encoding='utf8') names=[name+"\n" for name in names] 推倒表达式 返回一个list+\n f.writelines(names) f.flush() print(names) f.close()
④文件操作
#创建空文件,在文件open操作下,w模式也会创建当前打开而不存在的文件目标 os.mknod('test.txt') f = open('test.txt','w') #文件目录操作需要导入的包 import os,shutil ①获取Python脚本工作的目录路径: os.getcwd() print(os.getcwd()) ②返回指定目录下的所有文件和目录名:os.listdir() print(os.listdir()) #为空返回当前目录下的所有文件 print(os.listdir('股票数据')) #返回参数目录下的所有文件 ③删除一个文件:os.remove() print(os.remove('data.pkl')) #参数‘文件名’ ④删除多个目录:os.removedirs(r“c:\python”) ⑤检验给出的路径是否是一个文件:os.path.isfile() S = os.getcwd() print(S) l = os.path.isfile(S) print(l) ⑥检验给出的路径是否是一个目录:os.path.isdir() S = os.getcwd() print(S) l = os.path.isabs(S) print(l) ⑦判断是否是绝对路径:os.path.isabs() S = os.getcwd() print(S) l = os.path.isabs(S) print(l) ⑧检验给出的路径是否真地存:os.path.exists() S = os.getcwd() print(S) l = os.path.exists(S) print(l) ⑨返回一个路径的目录名和文件名:os.path.split() s = os.path.split('/home/swaroop/byte/code/poem.txt') print(s) >>>('/home/swaroop/byte/code', 'poem.txt') ⑽分离扩展名:os.path.splitext() ⑾获取路径名:os.path.dirname() ⑿获取文件名:os.path.basename() ⒀获取文件大小:os.path.getsize(filename) s = os.path.getsize('Test.txt') print(s) #其他附带: ''' 运行shell命令: os.system() 读取和设置环境变量:os.getenv() 与os.putenv() 给出当前平台使用的行终止符:os.linesep Windows使用'\r\n',Linux使用'\n'而Mac使用'\r' 指示你正在使用的平台:os.name 对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix' 重命名:os.rename(old, new) 获取文件属性:os.stat(file) 修改文件权限与时间戳:os.chmod(file) '''
⑤目录操作
#对应的包 import os,shutil @操作 ①创建目录:os.mkdir('file') ②创建多极目录:s.makedirs(r“c:\python\test”) ③删除目录(只能删除空目录):os.rmdir('file') ④删除目录(目录所有文件连同删除):shutil.rmtree('file') ⑤移动文件(目录):shutil.move('oldpos','newpos') ⑥重命名文件或者目录:os.rename('oldname','newname') ⑦复制文件夹:shutil.copytree('olddir','newdir') #oldfile只能是文件夹,且newfile必须不存在 ⑧复制文件:shutil.copyfile('oldfile','newfile') #oldfile和newfile都只能是文件 ⑨复制文件:shutil.copy('oldfile','newfile') #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录 ⑩转换目录:os.chdir('path') import os,shutil src = os.chdir('D:\\Date') #改变当前目录 l = os.getcwd() # 获取当前路径 print('当前的路径为:{}'.format(l)) x=open('test.txt','r') print(x.read()) x.close()
12.预定义的清理行为
# 上下文语法:在程序执行结束后关闭进程,释放资源 with open('test.txt') as f: for line in f: print(line)
13.python 对象:类(class)
#python类的属性: ①__private_attrs:两个下划线开头,声明该属性为私有,不能再类的外部被使用或直接访问。在类内部的方法中使用时self.__private.attrs @私有变量:__weight = 0 @共有变量:name = '' ②self参数:类的方法中必须包含self参数,且为第一个参数,self代表类的实例,可使用this替代但不可缺 # 类的实例: class MyClass: """一个简单的类实例""" i = 000 def f(self): return 'hello world' # 实例化类 x = MyClass() # 访问类的属性和方法 print("MyClass 类的属性 i 为:", x.i) print("MyClass 类的方法 f 输出为:", x.f()) >>> MyClass 类的属性 i 为: 000 MyClass 类的方法 f 输出为: hello world #__init__()方法:类的实例化操作会自动调用__init__()方法 def __init__(self): self.data = [] x= MyClass() #自动调用__init__()方法 #__init__()方法的参数 class complex: def __init__(self, realpart, imagpart) self.r = realpart self.i = imagpart x = complex(3,4) print(x.r,x.i) >>>3 4 # 类的方法: class people: name = '' age = 0 # 定义私有属性,私有属性在类外部无法直接进行访问 _weight = 0 def __init__(self, n, a, w): self.name = n self.age = a self.__weight = w def speak(self): print("{0} 说:我 {1} 岁了。".format(self.name,self.age)) # 实例化类 p = people('tom', 10,10) p.speak() >>>tom 说:我 10 岁了。 # 类的单继承: class people: name = '' age = 0 # 定义私有属性,私有属性在类外部无法直接进行访问 _weight = 0 def __init__(self, n, a, w): self.name = n self.age = a self.__weight = w def speak(self): print("{0} 说:我 {1} 岁。".format(self.name,self.age)) # 单继承 class student(people): grade = '' def __init__(self, n, a, w, g): # 调用父类的构造函数方法 people.__init__(self, n, a, w) self.grade = g # 覆写父类方法 def speak(self): print("{0} 说:我 {1} 岁了,我在读 {2} 年级".format(self.name, self.age, self.grade)) if __name__ == '__main__': s = student('tom', 10, 50 ,3) s.speak() >>>tom 说:我 10 岁了,我在读 3 年级 # 类的多继承: class student(people): grade = '' def __init__(self, n, a, w, g): # 调用父类的构造函数方法 people.__init__(self, n, a, w) self.grade = g # 覆写父类方法 def speak(self): print("{0} 说:我 {1} 岁了,我在读 {2} 年级".format(self.name, self.age, self.grade)) class speaker(): topic = '' name = '' def __init__(self, n, t): self.name = n self.topic = t def speak(self): print("我叫{0},今天我演讲的是{1}".format(self.name, self.topic)) # 多重继承 class sample(speaker, student): a = '' def __init__(self, n, a, w, g, t): # 调用people和speaker构造函数 student.__init__(self, n, a, w, g) speaker.__init__(self, n, t) # 重写父类方法 def speak(self): print("我叫{},今年 {} 岁,读{}年级,我是一个小说家,今天我演讲的是{}".format(self.name,self.age,self.grade,self.topic)) if __name__ == '__main__': s = sample('tom', 10, 50 ,3,'python') s.speak() # 方法重写:super()函数是用于调用父类(超类)的一个方法 class Parent: # 定义父类 def myMethod(self): print ('调用父类方法') class Child(Parent): # 定义子类 def myMethod(self): print ('调用子类方法') c = Child() # 子类实例 c.myMethod() # 子类调用重写方法 super(Child,c).myMethod() #用子类对象调用父类已被覆盖的方法 >>> 调用子类方法 调用父类方法 # 类的私有方法:__Method(self),私有方法不能被直接进行调用 def __foo(self): pass class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): print('name : ', self.name) print('url : ', self.__url) def __foo(self): # 私有方法 print('这是私有方法') def foo(self): # 公共方法 print('这是公共方法') self.__foo() x = Site('菜鸟教程', 'www.runoob.com') x.who() # 正常输出 x.foo() # 正常输出 x.__foo() # 报错 # 类的专有方法: (1).__init__():构造函数,在生成对象时调用 (2).__del__():析构函数,释放对象时使用 (3).__repr__():打印,转换 (4).__setitem__():按照索引赋值 (5).__getitem__():按照索引取值 (6).__len__():获取长度 (7).__cmp__():比较运算 (8).__call__():函数调用 (9).__add__():加运算 (10).__sub__():减运算 (11).__mul__():乘运算 (12).__truediv__():除运算 (13).__mod__():求余运算 (14).__pow__():乘方 # 运算符重载 class Vector: def __init__(self, a, b): self.a = a self.b =b def __str__(self): return 'Vector ({0},{1})'.format(self.a,self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) if __name__ == '__main__': v1 = Vector(3,4) v2 = Vector(5,6) print(v1 + v2)
浙公网安备 33010602011771号