知识点
-
函数与模块的关系:一个模块中可以包含N多个函数
-
在python中一个扩展名为 .py 的文件就是一个模块
-
模块的好处:1.方便其他程序和脚本的导入并使用
2.避免函数名和变量名冲突
3.提高代码的可维护性和可重用性
-
导入包的方式:1. from … import…(不常用)
-
- import … 3. pip install 包名 最常用的两种
编码格式:python的解释器使用的是Unicode(内存)
.py文件在磁盘上使用UTF -8存储(外存)
文件默认的字符编码是gbk ,只能读取英文的,比如一个a.txt文件 ,
如果要读取他里面的中文就要将他改为uft-8,后者在后面加上’UTF-8’
如果文件里面是英文,就可以直接读取,
而python中是utf-8 ,UTF-8可以支持中文的
改一个文件的编码直接在他最前面写encoding=gbk/unicode/utf-8
- gbk一个英文占一个字节,一个中文占两个字节
- UTF-8是英文占一个字节,一个中文占三个字节
- Unicode是两个字节表示一个字符
- r 是读 w是写 a是追加,rb 是以二进制读取 rw 以二进制写入
代码实现
包的导入方式
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/18 16:02
print('=====第一种导入方式=======')
import math #导入数学运算 导入所有的
print(type(math))
print(math)
print(math.pi)
print(math.pow(2,3)) #2的3次方
print(math.ceil(9.23324)) #取大的
print(math.floor(9.212323)) #取小的
print('=====第二种导入方式=======')
from math import pi #只导入pi的,其他的用不了
print(math.pi)
运行结果:
=====第一种导入方式=======
<class 'module'>
<module 'math' (built-in)>
3.141592653589793
8.0
10
9
=====第二种导入方式=======
3.141592653589793
文件的读写追加
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/19 15:28
print('====读======')
file=open('a.txt','r',encoding='UTF-8')
print(file.readlines())
print('=====写和追加======')
file=open('b.txt','w',encoding='UTF-8')
file.write('helloworld')
file=open('a.txt','a',encoding='UTF-8') #a表示追加
file.write('helloworld')
file.close()
运行结果:
====读======
['中国\n', '美丽']
=====写和追加======
读
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/21 9:14
print('=====读======')
file=open('a.txt','r',encoding='UTF-8')
# print(file.read()) #全部读取出来 中国 美丽
# print(file.read(2)) #读取前面两个 中国
# print(file.readline()) #读取第一行 中国
print(file.readlines()) #读取全部并以列表形式输出
file.close()
写
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/21 9:22
print('=====写=====')
file=open('c.txt','a')
# file.write('hello') #写入字符串
lst=['java','go','python']
file.writelines(lst)
file.close()
隔几个字符在读
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/21 9:27
file=open('a.txt','r',encoding='UTF-8')
file.seek(3) #UTF-8中一个中文占3个字节
print(file.read())
file.close()
with语句
# 教育机构 舒寒科技有限公司
# 学习者 舒寒拽少
# 学习时间: 2022/1/21 9:43
print('====with语句=========')
#使用with语句就不要在手动关闭了。用写file.close
with open('a.txt','r',encoding='UTF-8') as file:
print(file.read())