普通文件操作方式
1、文本文件写入
2、文本文件的读取
3、二进制文件的操作
1.将程序中的数据,写入到文件中
file = open("./data/1.1.text", "w", encoding="utf-8")
#程序中有一个字符串
message = "hello world"
#将数据写入到文件中
file.write(message)
#关闭文件
file.close()
2.将文件中的数据,读取到程序中
# 按照只读的方式打开文件
file = open(file = "./data/1.1.text", mode = "r", encoding="utf-8")
#从文件中读取数据,展示到控制台中
info = file.read()
print(info)
#关闭文件
file.close()
3.文本文件的追加
file = open(file = "./data/1.2.text", mode = "a", encoding ="utf-8")
#要操作的文本数据
message = "林深时见鹿,海蓝时见鲸,夜深时见你"
file.write(message)
message2 = "\n林深时雾起,海蓝时浪涌,夜深时梦续"
file.write(message2)
message3 = "\n你可知,鹿踏雾而来,鲸随浪而起,你未曾转身,怎知我已到来"
file.write(message3)
#关闭文件
file.close()
4.二进制文件的操作
#读取计算机中的二进制文件数据
file = open(file = "E:/picture/li2.jpg", mode = "rb")
#读取数据到程序中
#双引号字符串前面有个字母b表示的是二进制数据、字母u表示的是unicode数据
# \x开头的是十六进制数据、\o开头的是八进制数据。
print(file.read())
#将数据重新存储到我们指定的位置
file2 =open(file = "./data/test2.jpg",mode = "rb")
file2.write(file.read())
#关闭文件2
file2.close()
#关闭文件
file.close()
5.重要:文件的快捷操作—with语法
with open("E:/picture/li2.jpg", "rb") as file1:
#打开文件,将文件对象赋值给file1,with中的代码执行完成,文件自动关闭。
with open("./data/1.jpg", "wb") as file2:
#将读取的文件存储到指定的文件夹中
file2.write(file1.read())
6.字符串的切片操作
s1 = "helloworld"
s1[start:stop:step] #包含开头,不包含结尾
print(s1[1:])
—>elloworld
print(s1[1:3])
—>el
print(s1[::-1]) #字符串翻转
—>dlrowolleh
print(s1[3:1:-1])
—>ll
文件存取方法
eval()
1、将程序中的字典数据,转换成字符串存储到文件中
users = {"admin": {"username": "admin", "password": "123", "nickname": "老刘"}}
#类型能否直接转换成字符串?
users_str = str(users)
#存储到文件中
with open("./data/2.1.text", "w") as file:
file.write(users_str)
2、将文件中的字符串数据,读取到程序中
with open("./data/2.1.text", "r") as file:
users = file.read()
print(users, type(users)) #字符串类型
#将字符串数据,转换成字典:该字符串的格式和python中的字典的表达式一致
users = eval(users)
print(users, type(users)) #字典类型
print(users.get("admin"))
json
1、将程序中的数据,直接存储到文件中
import json
with open("./data/3.1.json", "w") as file:
json.dump(users, file)
2、将文件中的数据,读取到程序中
with open("./data/3.1.json", "r") as file:
users = json.load(file)
print(users, type(users))
marshal
1、存储多个数据到文件中
import marshal
# 数据准备
s = "字符串"
i = 19
f = 3.1415926
b= True
c = 12 + 5j
l = [1, 2, 3]
d = {"username": "admin", "password":"123"}
x = [s, i, f, b, c, l, d]
with open("./data/4.1.dat", "wb") as file:
#第一次存储一个数量:有多少个数据存储到了文件中
marshal.dump(len(x), file)
#存储每个数据
for x1 in x:
marshal.dump(x1, file)
2.将多个数据从文件中依次取出
with open("./data/4.1.dat", "r") as file:
n = marshal.load(file)
#将所有数据依次取出
for x in range(n):
print(marshal.load(file))
shelve
1.将多个数据按照key:value的形式存储到文件中
file["users"] = users
file["articles"] = articles
2.从文件中根据key读取数据
print(file["users"], type(file["users"]))