| 函数/方法 | 说明 |
| open | 打开文件,返回文件操作对象 |
| read | 将文件读取到内存 |
| write | 将指定内容写入文件 |
| close | 关闭文件 |
# 打开文件
file = open("C:\Users\wmk\Desktop\双周计划.txt", encoding="UTF-8")
# 读取文件
text = file.read()
print(text)
file.close()
# 写入文件
file1 = open(r"C:/Users/wmk/Desktop/双周计划.txt" ,"w")
str1 = "hello worldn"
file1.write(str1)
str1 = "hello pythonn"
file1.write(str1)
# 关闭文件
file1.close()
四、
open
打开
⽂
件的
⽅
式
open
函数默认以只读
⽅
式打开
⽂
件,并且返回
⽂
件对象
“r”:
只读方式打开文件
;
“w”:
只写方式打开文件
;
“a”:
追加写方式打开文件
;
open
函数的访问方式后面添加
b
参数代表访问二进制文件,
如:
rb:
代表用只读的方式打开一个二进制文件;
wb
:代表用只写的方式打开一个二进制文件。
ab
:代表用追加写的方式打开一个二进制文件。
五、
open
打开文件时指定字符集
open(
文件名
,
打开方式
, encoding=’
字符集
’)
。
1.
以
utf8
编码格式打开文件
如果指定文件字符集编码不是
utf8
,打开会报错
# 打开文件 file = open(r"C:filetempa.txt", "r", encoding="utf8")2. 以 gbk 编码格式打开文件 如果指定文件字符集编码不是 gbk ,打开会报错
# 打开文件 file = open(r"C:filetempa.txt", "r", encoding="gbk")按行读取文件内容
- read ⽅法默认会把⽂件的所有内容⼀次性读取到内存 ;
- 如果⽂件太⼤,对内存的占⽤会⾮常严重 ;
- 解决方案:按行读取文件内容。
# 打开文件 file = open(r"C:filetempa.txt") # 读取一行内容 text = file.readline() # 显示读取内容 print(text) # 关闭文件 file.close()三、结合 while 循环 readline 读取文件全部内容
# 打开文件
file = open(r"C:filetempa.txt")
while True:
text = file.readline()
if text == "":
# 如果已经读取到文件最后,循环结束
break
# 显示读取内容
print(text, end="")
# 关闭文件
file.close()
四、
readlines
⽅
法
readlines
方法可以一次读取文件所有行,返回类型为列表。
readlines
读取文件所有行内容,并显示文件全部内容
# 打开文件 file = open(r"C:filetempa.txt") # text 类型为 list,list 中每个成员就是文件 a.txt 的每一行 text = file.readlines() # 遍历列表 text for n in text: # 显示 text 每个成员内容 print(n) # 关闭文件 file.close()五、 with open 语法
f = open("a.txt", "r")
text = f.read()
print(text)
f.close()
以上代码等价
with open("a.txt", "r") as f:
text = f.read()
print(text)
JSON 操作
一、JSON 特点
- JSON 是纯文本;
- JSON 具有良好的自我描述性,便于阅读和编写
- JSON 具有清晰的层级结构;
- 有效地提升网络传输效率;
- 大括号保存对象;
- 中括号保存数组;
- 对象数组可以相互嵌套;
- 数据采用键值对表示;
- 多个数据由逗号分隔;
- JSON 值可以是:
- 数字(整数或浮点数);
- 字符串(在双引号中);
- 逻辑值(true 或 false);
- 数组(在中括号中);
- 对象(在大括号中);
- null
{"name": "tom",
"age": 18,
"isMan": True,
"school": null,
"address": {
"country": "中国",
"city": "上海",
"street": "高泾路"
},
"numbers": [2, 6, 8, 9],
"links": [
{
"name": "王小柯_0314",
"url": "https://blog.csdn.net/wwwkm123?type=blog"
}
]
}
四、json 数据操作
1. JSON
文件读写
读取
JSON
文件
import json
f = open('a.json', "r", encoding='UTF-8')
data = json.load(f)
# 返回的 data 数据类型为字典或列表
print(data)
f.close()
写入
JSON
文件:
import json
data = {'name': 'tom', 'age': 20, 'country': '中国'}
f = open('temp.json', 'w', encoding='UTF-8')
json.dump(data, f, ensure_ascii=False)
# ensure_ascii=False 代表中文不转义
f.close()
2.
课堂练习
1.
文件
test.json
内容如下:
{ "name": "诸葛亮", "sex": "男", "age": 24 }
2.
利用
json.load
与
json.dump
将
age
的值修改为
30
# 思路:
# 先把内容从test.json文件中读出来
# 读出来的结果是一个字典
# 把字典中键age对应 的值修改为30
# 再把字典写回到test.json文件中
import json
file = open("test.json", "r", encoding="utf8")
dict1 = json.load(file)
file.close()
dict1["age"] = 30
file = open("test.json", "w", encoding="utf8")
json.dump(dict1, file, ensure_ascii=False)
file.close()



