1.open的使用
# 操作文件流程
# 1 打开文件(文件路径, 模式)
# 2 操作文件
# 3 关闭文件
# f = open("data.txt", mode="r")
# print(f.readable())
# # content = f.read()
# # print(type(content))
# # line = f.readline()
# # print(type(line))
# content = f.readlines()
# print(type(content), content)
# f.close()
# f = open("image.png", "rb")
# content = f.read()
#
# f1 = open("image_new.png", "wb")
# f1.write(content)
# f1.close()
#
# f.close()
# f = open("data1.txt", mode="w")
# # print(f.writable())
# # f.write("this is new content")
# f.writelines([
# "hello\n",
# "hi\n",
# "welcome"
# ])
# f.close()
# f = open("data2.txt", "x")
# f.write("heillo123456")
# f.close()
# f = open("data3.txt", "a")
# f.write("456789")
# f.close()
# 随着代码块的结束 f自动关闭 不需要调用close
with open("data.txt", mode="r") as f:
print(f.read())
2.json的使用
# import json
#
#
# def save_data():
# datas = {
# "students": [
# {
# "id": 101
# },
# {
# "id": 102
# }
# ]
# }
#
# # # 将字典序列化成字符串
# # datas_str = json.dumps(datas)
# # # print(datas_str, type(datas_str))
# # with open("data.txt", "w") as f:
# # f.write(datas_str)
#
# with open("data.txt", "w") as f:
# json.dump(datas, f)
#
#
# save_data()
#
#
# # def load_data():
# # # with open("data.txt", "r") as f:
# # # content = f.read()
# # # content = json.loads(content)
# # # print(content, type(content), len(content["students"]))
# #
# #
# # with open("data.txt", "r") as f:
# # content = json.load(f)
# # print(content, len(content["students"]))
# #
# # load_data()
import json
import os
result = {
"students": [],
"class": [],
"score":[],
"user":[]
}
def read_data():
if os.path.exists("data.txt"):
with open("data.txt", "r") as f:
global result
result = json.load(f)
read_data()
def save_date():
global result
result["students"].append({
"id": result["students"][-1]["id"] + 1 if result["students"] else 101,
"name": input("输入用户名")
})
with open("data.txt", "w") as f:
json.dump(result, f)
save_date()
# 闭包
# 1. 外部函数嵌套内部函数
# 2. 外部函数将内部函数
# 3. 内部函数可以访问保存外部函数局部变量
import time
# def f1():
# print("f1")
# i = 0
#
# def f2():
# nonlocal i
# i += 1
# print("f2", i)
#
# return f2
#
#
# r = f1()
# r()
# r()
# r()
# def time_calc(f):
# def calc():
# start = time.time()
# f()
# print(time.time() - start)
#
# return calc
#
#
# def login_required(f):
# def check():
# username = input("输入用户名")
# if username == "admin":
# f()
# else:
# print("校验失败,去登录")
#
# return check
#
# @login_required
# @time_calc
# def index():
# print("欢迎来到首页")
#
# # index = login_required(index)
# # index = time_calc(index)
#
# index()
# 数据的存储:文件、数据库:内容均是文本形式或者是二进制形式
# 程序中的数据是对应的数据类型? 该怎么存储
# 需要一种技术将程序中的数据 与 文件中的数据进行转换
# 序列化:将对象(字典、列表)转字符串
# 反序列化:将字符串转对象(字典、列表)
import json
import pickle
# 符合json格式的字符串
# s0 = '[{"id":101, "name":"王石"},{"id":102, "name":"王健林"}]'
# obj = json.loads(s0)
# print(type(obj), obj[0]["name"])
# with open("data.txt", "r+", encoding="UTF8") as f:
# # content = f.read()
# # obj = json.loads(content)
#
# obj = json.load(f)
# print(type(obj), obj[0]["name"])
# # 将文件指针放在开头 覆盖原有内容
# f.seek(0)
# obj.append({
# "id": obj[-1]["id"] + 1 if obj else 101,
# "name": input("输入用户名")
# })
#
#
# # s = json.dumps(obj, ensure_ascii=False)
# # f.write(s)
#
# json.dump(obj, f, ensure_ascii=False)
#
#
#
# # print(f.readable(), f.writable())
3.open的使用案例
with open('example.txt', 'r') as f:
content = f.read()
print(content)
4.json使用案例
import json
# 将 Python 对象转换为 JSON 字符串
data = {
'name': 'Alice',
'age': 25,
'is_student': True,
'courses': ['Math', 'English', 'Science']
}
json_str = json.dumps(data)
print(json_str)
# 将 JSON 字符串转换为 Python 对象
json_data = '{"name": "Bob", "age": 30, "is_student": false, "courses": ["History", "Geography"]}'
data = json.loads(json_data)
print(data)
{"name": "Alice", "age": 25, "is_student": true, "courses": ["Math", "English", "Science"]}
{
'name': 'Bob',
'age': 30,
'is_student': False,
'courses': ['History', 'Geography']
}