ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python基础知识-day7(文件操作)

2022-06-17 17:06:26  阅读:211  来源: 互联网

标签:文件 utf python day7 str1 bytes 基础知识 print open


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("无论如何我都被输出")

 

标签:文件,utf,python,day7,str1,bytes,基础知识,print,open
来源: https://www.cnblogs.com/cch6842/p/16386324.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有