目录
②read() 读取文件 readlines()方法 readline()
一、文件
1、文件的操作
①open() 打开函数
- open函数,可以打开一个已经存在的文件,或者创建一个新文件
- open(name, mode, encoding)
- name:要打开的文件的名(可以包含文件所在的具体路径)
- mode:设置打开文件的模式(访问模式):只读、写入、追加等
- encoding:编码格式(UTF-8)
r:以只读模式打开文件。
w:打开一个文件只用于写入。(原有内容会被删除,如果该文件不存在,创建新文件)
a:打开一个文件用于追加。(如果该文件已存在,新内容在旧内容之后;如果不存在,创建新文件进行写入)
# 打开文件
f=open('D:/1研究生学习/python.txt','r',encoding="UTF-8")
print(type(f))
②read() 读取文件 readlines()方法 readline()
- 文件对象.read(num)
- num:从文件中读取的数据的长度(单位是字节),如果没有num,表示读取文件中的所有的数据
- readlines可以按照行的形式把整个文件中的内容进行一次性读取,并返回一个列表
- readline:一次读取一行
# 读取文件 会有指针,下一次是在上一次的结束处 开始
# print(f"{f.read()}")
# lines=f.readlines()
# print(f"{lines}")
print(f"{f.readline()}")
print(f"{f.readline()}")
# 遍历 读取每一行
for line in f:
print(line)
③文件关闭 close()
- f.close()
f.close()
④with open() as f 打开文件,可以自动关闭
with open('D:/1研究生学习/python.txt','r',encoding="UTF-8") as f:
for line in f:
print(line)
⑤、文件写入 write() flush()
f=open('D:/1研究生学习/python.txt','w',encoding="UTF-8")
f.write("hello")
//将内存积攒的内容写入文件中
f.flush()
f.close()
不写flush,只写close是一样的
二、异常
1、异常的捕获
- 捕获普通异常
try:
可能发生错误的代码
except:
如果出现异常执行的代码
//例如:
try:
f=open("D:/aa.txt","r",encoding="UTF-8")
except:
f=open("D:/aa.txt","w",encoding="UTF-8")
- 捕获指定异常
try:
print(name)
except NameError as e:
print("出现了变量未定义异常")
print(e)
- 捕获多个异常
try:
1/0
except (NameError,ZeroDivisionError) as e:
print("出现了变量未定义异常")
print(e)
try:
1/0
except Exception as e:
print("全部异常")
print(e)
- else
try:
1/5
except Exception as e:
print(e)
else:
print("无异常")
- 异常的finally 无论是否异常,都必须执行该语句
try:
1/5
except Exception as e:
print(e)
else:
print("无异常")
finally:
print("必须执行")
2、异常的传递
def fun1():
print("fun1")
num=1/0
print("1结束")
def fun2():
print("fun2")
fun1()
print("2结束")
def main():
try:
fun2()
except Exception as e:
print(e)
main()
# 结果:
# fun2
# fun1
# division by zero
三、模块 .py 文件
1、模块概念及导入
- import 模块名
- from 模块名 import 类、变量、方法等
- from 模块名 import *
- import 模块名 as 别名
- from 模块名 import 功能名 as 别名
① 使用import 导入time模块,使用sleep功能
# 中间睡眠5秒
import time
print("你好")
time.sleep(5)
print("我就")
②使用from导入time的sleep功能
from time import sleep
print("你好")
sleep(5)
print("我就")
③ 使用 * 导入time模块的全部功能
from time import *
print("你好")
sleep(5)
print("我就")
④ 使用 as 给特定功能加上别名
from time import sleep as ll
print("你好")
ll(5)
print("我就")
import time as ll
print("你好")
ll.sleep(5)
print("我就")
2、自定义模块
- _all_ :如果一个模块文件中有这个变量,当使用import导入时,只能导入这个列表中的元素
四、python包 文件夹
1、自定义包
① 方法一
- import 包.模块 包.模块.函数
- from 包 import 模块 模块.函数
- from 包.模块 import 函数 函数
② 方法二
- 必须在 _init_.py 文件夹中添加 _all_ = [ ] ,控制允许导入的模块列表
- 控制 import * 能够导入的内容
2、安装第三方包
- 科学计算中:numpy包
- 数据分析中:pandas包
- 大数据计算中:pyspark包、apache-flink包
- 图形可视化:matplotlib、pyecharts
- 人工智能:tensorflow
方法一:
① pip install 包名称
②pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 包名称
方法二: