1.模块管理函数和类
1)模块
一个.py文件就是一个模块
2)import
可以通过import关键字导入其他的模块
格式: import 模块名(.py文件)
直接导入模块的时候,相当于把被导入模块里面的内容粘贴到了import的位置
3)使用模块中的内容,及什么内容是可以使用的
模块名.变量的方式去使用模块中的内容,在模块中声明的全局变量可以使用(普通变量、函数、类)
4)from 模块 import 内容1,内容2,...-->导入模块中所有的内容但只有指定的内容可以使用
使用内容的时候,不用在被导入的变量或者函数或者类前
加模块名
5)阻止导入
- 阻止被导入模块中的不必要的代码被粘贴到当前模块中.一般情况下,除了函数的声明和类的声明以外,其他的代码都放到这个if里面
f __name__ == '__main__':
这个里面的代码不会被其他模块使用
pass
-
name属性:是每个模块自带的一个属性,是用来保存当前
模块的名字的,但是执行当前模块的时候
这个属性的值是固定的'main'
6)使用as重命名
import 模块名 as 新的名字
from 模块名 import 函数名 as 新的函数名
01-模块管理函数和类.py
if __name__ == '__main__':
# 这个里面的代码不会被其他模块使用
pass
print('==============')
import other
# 在模块中声明的全局变量可以使用(普通变量、函数、类)
other.func_other()
print(other.name,other.item)
print(other.__name__)
print(__name__)
print('==============')
from other2 import func2
func2()
# import math as my_math
# print(my_math.pi)
from math import pi as get_pi
print(get_pi)
# 练习:使用一个模块,用来管理所有和形状相关的功能
# (求两个点之间的距离、求元的周长、求园的面积、求矩形的周长和面积等)
from graph import get_dis,circle_area,circle_perimeter,rectangle_area,rectangle_perimeter,get_point
def get_graph(type):
if type=='俩点距离':
return get_point,get_dis
if type=='圆周长':
return circle_perimeter
if type=='圆面积':
return circle_area
if type=='矩形周长':
return rectangle_perimeter
if type=='矩形面积':
return rectangle_area
print(get_graph('俩点距离')[1](get_graph('俩点距离')[0](1,2),get_graph('俩点距离')[0](5,7)))
print(get_graph('圆周长')(5))
print(get_graph('圆面积')(5))
print(get_graph('矩形周长')(5,8))
print(get_graph('矩形面积')(5,7))
graph.py
if __name__ == '__main__':
# 这个里面的代码不会被其他模块使用
pass
print('==============')
import other
# 在模块中声明的全局变量可以使用(普通变量、函数、类)
other.func_other()
print(other.name,other.item)
print(other.__name__)
print(__name__)
print('==============')
from other2 import func2
func2()
# import math as my_math
# print(my_math.pi)
from math import pi as get_pi
print(get_pi)
# 练习:使用一个模块,用来管理所有和形状相关的功能
# (求两个点之间的距离、求元的周长、求园的面积、求矩形的周长和面积等)
from graph import get_dis,circle_area,circle_perimeter,rectangle_area,rectangle_perimeter,get_point
def get_graph(type):
if type=='俩点距离':
return get_point,get_dis
if type=='圆周长':
return circle_perimeter
if type=='圆面积':
return circle_area
if type=='矩形周长':
return rectangle_perimeter
if type=='矩形面积':
return rectangle_area
print(get_graph('俩点距离')[1](get_graph('俩点距离')[0](1,2),get_graph('俩点距离')[0](5,7)))
print(get_graph('圆周长')(5))
print(get_graph('圆面积')(5))
print(get_graph('矩形周长')(5,8))
print(get_graph('矩形面积')(5,7))
other.py
def func2():
print('~~~~~')
global item
item='kjfhg'
# 在这儿写当前模块汇总不需要被其他模块导入和粘贴的代码
if __name__=='__main__':
name = 1011
print(name)
other2.py
def func2():
print('~~~~~')
global item
item='kjfhg'
# 在这儿写当前模块汇总不需要被其他模块导入和粘贴的代码
if __name__=='__main__':
name = 1011
print(name)
结果:
==============
10
other
=======
10 sg
other
main
==============
~~~~~
3.141592653589793
6.4031242374328485
31.41592653589793
78.53981633974483
26
35
2.文件基本操作
(所有)文件操作流程:打开文件->操作文件(读/写)-->关闭文件
1)打开文件:
open(文件路径,打开的方式(读方式/写方式),编码方式)
文件路径(必填):决定打开那个文件
打开方式(默认值是'r'):决定打开文件后是进行什么样的操作
-
'r'-读操作(读出来是字符串)
-
'rb'/'br'-读操作(读出来的是二进制)(音频视频图片)
-
'w'-写操作(可以将文本数据写入文件中) 写的时候会清空文件中原来的内容然后再往里写数据
-
'wb'/'bw'-写操作(可以将二进制数据写入文件中)
-
'a'-写操作(追加) 在原文件内容的最后添加内容
-
编码方式:主要针对文本文件的读写(不同的操作系统
默认的文本编码方式不同,windows->gbk,mac->utf-8)
2)文本文件读写
- 放到工程外面的文件(绝对路径)
- 将文件放到工程目录下的某个位置(相对路径)
格式:open(./相对路径 或者 ../相对路径)
当py文件直接放在工程目录下,想要使用open打开工程
中的其他文件使用'./'
当py文件在工程目录下面,想要使用open打开工程中的其
他文件使用'../'
- 绝对路径
open('D:\Python项目\Day9-文件操作\code\graph.py')
- 相对路径
open('./graph.py')
# open('./venv/Lib/site-packages/setuptools.pth')
3)打开文件
打开文件,返回文件句柄(文件代言人)
注意:以读的方式打开文件,如果这个文件不存在,会报错FileNotFindError:
以写的方式打开文件,如果这个文件不存在,就会创建这个文件
f=open('./graph.py','r',encoding='utf-8')
4)获取文件内容
文件.read():获取文件内容,并且返回
read(n)-->n设置读取的长度
读文件有记录功能,先读3个字符,第二次就从第四个字符开始读
content=f.read()
print(open('./text1.txt','r',encoding='utf-8').read())
# 关闭文件
open('./text1.txt', 'r', encoding='utf-8').close()
结果:
you are sb
5)文本文件的写操作
w=open('./text1.txt','w',encoding='utf-8')
w.write('疑是地上霜1')
6)二进制文件的读写操作
音频、视频、图片文件,都是二进制文件
# 1)打开文件
imag=open('./fubo.jpg','br')
# 读文件
im=imag.read()
# bytes:python中二进制数据对应的数据类型
# print(type(im),im)
#关闭文件
imag.close()
# 写文件
f=open('.fubo1.jpg','wb')
f.write(im)
f.close()
7)通过with关键字去打开文件
with open()as 文件变量名:
文件操作
# 写
with open('./text1.txt','w',encoding='utf-8') as wr:
wr.write('you are sb')
# 读
with open('./text1.txt', 'r', encoding='utf-8') as fix:
str = fix.read()
print(str)
结果:
hello person
with open('d:/Documents/MATLAB/add-noise/lena.bmp','br') as im:
imag=im.read()
print(imag)
with open('./lena.bmp','wb') as bmp:
bmp.write(imag)
with open('./lena.bmp','br') as bm:
bnp=bm.read()
print(type(bnp),bnp)
3.json文件
json文件(文件),就是文件后缀是.json的文件。内容必须是json格式的内容
1)json格式:
- 内容是字符串
- 最外层是字典,字典里面就必须是键对
- 最外层是数组(列表),数组里面的内容必须是数组数据
*json是python中内置的一个模块,专门用来处理json数据的
import json
if __name__ == '__main__':
'''json文件的读操作'''
# with open('./files/text.json','r',encoding='utf-8') as f:
# 直接使用read()去读,获取到的是字符串数据,包含json
# 文件中的所有的内容(包含注释部分)
# conten=f.read()
# print(conten,type(conten))
# 最外层只能是一个字典/一个数组/一个字符串
# 支持的数据类型:字符串("abc"),数字(34,35.6),布尔值(true/false),
# 数组([1,2,3,"b"]),字典({"df":'df',"gh":34}),null(None)
#
# load(文件对象):获取指定json文件中的内容
# json数据类型
# dict--->dict
# array--->list
# string--->str
# number--->int/float
# true/false--->True/False
# null--->None
# conten=json.load(f)
# print(conten['score'][0])
- json文件写操作
# with open('./files/text.json','w',encoding='utf-8') as w:
# # 写数据
# '''
# dump(写的内容,文件对象)
# '''
# write={"游戏":"王者",'玩家':'少年'}
# json.dump(write,w)
# with open('./files/text.json','r',encoding='utf-8') as di:
# dict1=json.load(di)
# print(dict1)
结果:
{'游戏': '王者', '玩家': '少年'}
练习:输入学生的姓名和电话,保存到本地(要求下次启动程序,再添加学生
信息还)
name=input('名字:')
tel=input('电话:')
student={'name': "name", 'tel': tel}
try:
with open('./files/text1.json', 'r', encoding='utf-8') as t:
list1 = json.load(t)
except FileNotFoundError:
list1=[]
list1.append(student)
with open('./files/text1.json','w',encoding='utf-8') as f:
json.dump(list1,f)
with open('./files/text1.json','r',encoding='utf-8') as f:
re=json.load(f)
print(re)
结果:
名字:da
电话:2415
[{'name': '李四', 'tel': '2325'}, {'name': 'name', 'tel': '2415'}]
- json模块的其他操作
json.loads(字符串,编码方式),将指定的字符串(json字符串),转化成json
将字符串转化成字典,将字符串转化成列表
json.dumps将json对象转换成json字符串字典/列表转换成json字符串
content=json.loads('["a",100,false,{"a":1,"abc":100}]',encoding='utf-8')
print(content,type(content))
content2=json.dumps(['aaa',1,True])
print(content2,type(content2))
['a', 100, False, {'a': 1, 'abc': 100}] <class 'list'>
["aaa", 1, true] <class 'str'>
4.异常
出现异常(错误)不想让程序崩溃,就可以进行一次捕获
try:
需要捕获异常的代码
except :
出现异常会执行的代码
try:
需要捕获异常的代码
except 错误类型:
捕获指定的错误才会执行的代码
ry:
需要捕获异常的代码
except (错误类型1,错误类型2,错误类型3...):
捕获指定的多个错误才会执行的代码
注意:异常捕获只有程序员清楚会出现异常,并想要自己来处理异常,而不是让程序崩溃的情况下才异常捕获。
使用捕获的时候,不能让except直接捕获所有的异常,而是捕获特定异常
import json
if __name__ == '__main__':
try:
with open('./aaa.txt','r',encoding='utf-8') as f:
pass
except FileNotFoundError:
with open('./aaa.txt','w',encoding='utf-8') as f:
json.dump(f)
网友评论