Exception
D:\pr\python\venv\Scripts\python.exe D:/pr/python/11.py
Traceback (most recent call last):
File “D:/pr/python/11.py”, line 1, in
1/0
# file ('that module', that line.)
ZeroDivisionError: division by zero #Code error reminder
Type
Handling exception
try:
1/0
except ZeroDivisionError as mingzhi:
print('除法除数有问题,请修改') #重定向
Combine with else
try:
1/0
except ZeroDivisionError as mingzhi:
print('除法除数有问题,请修改') #重定向
print(mingzhi )
else:
print('else')
try-except grammar rules
try:
# 可能出现异常代码
except:
# 如果说出现了异常,则代码立刻就进入except
finally:
必须要执行的代码(finally关键字:最后、最终的意思必须要执行的代码)
例:
```clike
try:
x=2
x+=10
except Exception as e :
print("程序有问题")
finally:
print("不管你怎么写,我的优先级很高")
x+=20
print(x)
(Note: If the return keyword is before finally, finally cannot change return. Return will be output as usual . Interview questions)
Example:
def addition():
try:
x=1
return x
except Exception as e:
print("有问题")
finally:
print("优先级高,但改变不了return")
x+=10#改变不了return值
return x
if __name__ == '__main__':
print(addition())
Exception handling
def func_with_l():
try:
l=[1,2,3]
#如果程序出现错误,错误出现后,后面程序将不会被执行。
l[3]#溢出
1/0#语法错误,0不能为除数
#多个except时,谁第一个找到问题,就输出谁,找不到就跳过。
except Exception as w :#Exception所以异常的总和
print('+'*10)
# except ZeroDivisionError as e:
# print('+'*20)
#except IndexError as ex:
# print(2*2)
if __name__=='__main__':
func_with_l()
O stream
1, what is IO stream
IO Stream(input output stream):
狭义上:内存和永久存储设备之间数据流动
广义上:内存和(其他电脑|其他存储设备)间数据的交互
2. How does python operate the IO
open function
open函数返回的是文件对象(File)
'buffer', 'close', 'closed', 'detach', 'encoding', 'errors',
'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name',
'newlines', 'read', 'readable', 'readline', 'readlines',
'reconfigure', 'seek', 'seekable', 'tell', 'truncate',
'writable', 'write', 'write_through', 'writelines']
Classification of IO streams
According to the direction of data flow:
|-- Input stream input
|-- Output stream output
Type of installation data:
|-- Bytes IO
|-- Character stream String IO
Character stream: the data type is string t==text
Byte stream:
open open, the mode needs to be defined b == binary binary
Use of pass keyword
from io import BytesIO
from io import StringIO
Object serialization
What is called serialization (Serialization):
These essences of object-oriented objects are logical concepts—>physical concepts
Either serialize the object into byte data, or serialize a string (json)
pickle
dump
load
dumps
loads
#官方提供的对象序列化的内置模块
import json#
import pickle
ls=[1,2,3,4,5,6,7,8]
pickle.dump(ls,open("路径或文件",mode="wb"))#持久化数据,将ls放在路径下
pickle.load(open("文件",mode="br"))#反序列化读取数据
a=pickle.dumps(ls)#返回序列化字节
print(pickle.loads(a))#序列化到处
#json方法和pickle方法一样
json.dumps(ls,open("路径",mode="wt"))#将ls放在路径下字符串保存
json.loads(open("路径",mode="r"))
Python file operation
import queue as q#文件导入
定义查找文件
import os.path as q#文件导入
#File read and write
#open a file
try:
file_path=input('请输入路径')
if q .exists (file_path ):
f=open(file=file_path )#打开并返回文件句柄
print( file_path )#非字节精确读数
print(f.readlines()=='' )#超过边界返回字符串,空字符
except IOError as e:
raise e
finally:
f .close() #函数的释放
Method Two
with open(file= 'e : 路径' ) as f :
print(f.readlines() )
Modify the file (the content will be emptied)
with open(file= 'e:/readme.txt ',mode= 'w' ) as f :
f.write('whrist')
File content increase (do not change the content inside)
with open(file= 'e:/readme.txt ',mode= 'a' ) as f :
f.write('whrist')
View the file handle offset position (seek, tell)
import os.path as q#文件导入
#文件读写
#打开一个文件
with open(file= 'e:/readme.txt ',mode= 'w+' ) as f :
f.write('我喜欢你')
#f.seek(0)#强制读文件从某一个位置开始
print(f.tell() )#偏移量位置,字符为单位
print(f.readlines() )
其他用法
import os.path as q#文件导入
with open(file= 'e:/readme.txt ',mode= 'ab+' ) as f :
f.write('I love you'.encode() )
f.seek(0)#强制读文件从某一个位置开始
print(f.tell() )#偏移量位置,字符为单位
print(f.readlines() )
View module path
import os #文件导入
print(os.path)#查看当前工作路径
import os #文件导入
print(os.getcwd() )#查看当前工作区
import os #文件导入
print(os. getcwd() )#查看当前工作区
os.chdir('路径') #改变工作目录
print(os. getcwd() )
Delete directory
import os
os. remove('目录') #删除一个目录
change name
import os
os. remove('目录名字,名字') #修改一个目录名字
Create a directory
import os
os.chdir('e:/') #工作目录
os. mkdir('文件名') #创建一个目录名字,当前工作区下创建
Create a file import os
os.chdir('e:/') #工作目录
os.makedirs('文件名') #创建一个文件名字,当前工作区下创建
import os
import os.path as op
os.chdir('e:/') #工作目录
os.makedirs('文件名') #创建一个目录名字,当前工作区下创建
print(op.isdir()) ##判断是否为目录
print(type (op.basename()) )# 获取路径或目录的直接名称,不要文件名和目录名
op.abspath() #
op.dirname() #获取路径或目录的直接名称,要文件名目录名
op.getatime() #
Programming experiment (calculate file size)
1. Clarify your needs (what you want to do)
#查找目录下目录。文件和文件大小,递归查看
import os
import os.path as op
dir_total_size=0#计算目录个数
file_total_size=0#计算在文件总大小
def guanzhe(root):
'''
rooot:给的目录,查看目录下所以子目录和文件
'''
global dir_total_size
for child in os.listdir():
item=op.join(root,child)
if op.isdir(child) :
global dir_total_size
dir_total_size +=1
guanzhe(item )
else:
global file_total_size
file_total_size +=op.getsize(child)
def showMess():
print('dir_total_size=%d'%dir_total_size )
if __name__=='__main__':
guanzhe(input('请输入目录') )
showMess( )