python基础知识-day7(文件操作)
2024-10-20 16:48:01
1、文件IO操作:
1)操作文件使用的函数是open()
2)操作文件的模式:
a.r:读取文件
b.w:往文件里边写内容(先删除文件里边已有的内容)
c.a:是追加(在文件基础上写入新的内容)
d.b:二进制的模式写文件
2、open函数执行流程:
1)open操作文件的时候,它的判断逻辑是:
a.如果是读的模式,文件必须得存在
b.如果是写得模式,文件不存在,open内部会自动创建一个文件,然后把内容写进去
3、操作文件的步骤:
1)打开文件
2)编辑文件
3)关闭文件
4、w模式的程序案例
1 def open_w():
2 f=open(file="log",mode="w",encode="utf-8")
3 f.write("学习Python")
4 f.close()
5 open_w()
5、多行写入
1 def open_ws():
2 f_read=open(file="log",mode="r",encode="utf-8")
3 f_write=open(file="log.txt",mode="w",encode="utf-8")
4 for item in f_read.readlines(): #按行读取
5 f_write.writes(item) #按行写入
6 f_read.close()
7 f_write.close()
8 open_ws()
6、a模式的程序案例
1 def open_a():
2 f=open(file="log",mode="a",encode="utf-8")
3 f.write("继续加油!")
4 f.close()
5 open_a()
7、r模式的程序案例
1 def readFile():
2 f=open(file="log",mode="r",encoding="utf-8")
3 print(f.read()) #读取文件里边所有内容
4 print(f.readline()) #读取文件里边第一行内容
5 for item in f.readlines():
6 print(item.strip())
7 f.close()
8 readFile()
8、编码和解码
编码:就是把str的数据类型转为bytes的数据类型的过程,使用的关键字是endcode;
解码:把bytes的数据类型转为str的数据类型的过程,使用的关键字是decode。
9、编码和解码的程序
1 str1=“加油!”
2 str1_bytes=str1.encode("utf-8") #编码
3 print(str1_bytes)
4 print(type(str1_bytes))
5
6
7 bytes_str1=str1_bytes.decode("utf-8") #解码
8 print(bytes_str1)
9 print(type(bytes_str1))
10、网站数据解码
1 import requests
2 r=requst.get(url="https://www.gushiwen.cn/")
3 print(r.content.decode("utf-8"))
11、with上下文(可代替close文件的作用)
1 def withFile():
2 with open(f="log.txt",mode="r",encoding="utf-8") as f:
3 print(f.read())
4 withFile()
5
6 def withFile():
7 with open(f="log.txt",mode="w",encoding="utf-8") as f:
8 print(f.write("加油"))
9 withFile()
12、异常管理
1 try:
2 1/0
3 score=int(input("输入成绩:\n"))
4 except ZeroDivisionError as e: #捕获异常
5 print(e.arg[0]) #获取异常信息
6
7 except Exception as e: #捕获异常
8 print(e.arg[0]) #获取异常信息
9 else:
10 print("try执行正常")
11 finally:
12 print("无论如何我都被输出")
最新文章
- 时间管理的若干Tips
- Hadoop简介
- IOS图像拉伸解决方案
- gulp-notify处理报错----gulp系列(二)
- Unity3D 多平台 预编译 宏定义
- CAS Proxy 的相关文章
- uva 10036 Problem C: Divisibility
- 费马小定理&;欧拉定理
- 《编程珠玑》第二章 aha算法
- JS模式---发布、订阅模式
- Django - 模式、简单使用
- Java 多线程概述
- win10 Faster-RCNN训练自己数据集遇到的问题集锦 (转)
- cf 700e(sam好题,线段树维护right)
- SQL Server 2012使用Offset/Fetch Next实现分页
- SC1243sensor噪点问题调试
- 从头认识Spring-1.14 SpEl表达式(1)-简单介绍与嵌入值
- [转]Python多线程与多线程中join()的用法
- asp.net利用QQ邮箱发送邮件,关键在于开启pop并设置授权码为发送密码
- Redis Key操作