1.數(shù)據(jù)本地化和數(shù)據(jù)持久化 - 通過文件將數(shù)據(jù)存到硬盤中
- 數(shù)據(jù)庫文件、txt台汇、json、plist谁撼、xml蒜绽、png文件镶骗、MP4、mp3等
2.文件操作 - 文件內(nèi)容操作
- 基本步驟: 打開文件 --> 操作文件(讀/寫) --> 關(guān)閉文件
1)打開文件
open(file, mode, encoding=None) - 以指定方式打開指定文件躲雅,并且返回被打開的文件對象
file -- 字符串,需要打開的文件的路徑
./ -- 當(dāng)前文件所在目錄(./可以省略)
../ -- 當(dāng)前文件所在目錄的上層目錄
mode -- 字符串,打開方式
r -- 默認(rèn)值鼎姊,以讀的方式打開文件(只能進行讀操作), 讀出來的是文本
w -- 以寫的方式打開文件(只能進行寫操作), 覆蓋
a -- 以寫的方式打開文件(只能進行寫操作), 追加
rb/br -- 以讀的方式打開文件(只能進行讀操作)相赁,讀出來的內(nèi)容是二進制數(shù)據(jù)
wb/bw -- 以寫的方式打開文件(只能進行寫操作)相寇,將二進制數(shù)據(jù)寫入文件中
+ -- 以讀寫的方式打開(了解)
encoding -- 文本編碼方式
utf-8
注意:文本編碼只針對文本文件、二進制文件不能設(shè)置編碼方式
2)文件操作
文件對象.read() -- 從讀寫位置開始噪生,讀到文件結(jié)尾,并且返回
(讀寫位置默認(rèn)在文件開頭)文件對象.seek(字節(jié)數(shù)) -- 將讀寫位置移動到指定的地方(了解)
def main():
# ================1.文件讀操作==================
# 1)read
f = open('./files/test.txt', 'r', encoding='utf-8')
result = f.read()
print(result, type(result))
# 將讀寫位置移動到文件開頭
f.seek(0)
result = f.read()
print('====:', result)
# 2) readline: 讀一行裆赵,字符串
f.seek(0)
print('讀一行:', f.readline())
print('讀一行:', f.readline())
# 練習(xí): 一行一行的將文件中的內(nèi)容讀完
f.seek(0)
while True:
result = f.readline()
if not result:
break
print(result)
# 3)readlines:一行一行讀所有,列表
f.seek(0)
print(f.readlines())
f.close()
# ================2.文件寫操作==================
文件對象.write(寫的內(nèi)容) - 將指定內(nèi)容寫入到指定文件中,返回被寫入的內(nèi)容的長度
f = open('./files/test.txt', 'w', encoding='utf-8')
result = f.write('abc')
print(result)
# 關(guān)閉文件
f.close()
- 注意: 打開文件的時候跺嗽,如果以讀的方式打開一個不存在的文件战授,會出現(xiàn)異常,報錯
- 如果以寫的方式打開一個不存在的文件桨嫁,不會出現(xiàn)異常植兰,并且會自動創(chuàng)建對應(yīng)的文件再打開
f1 = open('./files/test4.txt', 'w', encoding='utf-8')
1.二進制文件操作
rb - 讀的時候獲取到的是二進制數(shù)據(jù)(bytes)
wb - 寫的時候?qū)懭氲膬?nèi)容要求類型是二進制文件
普通的文本文件可以通過二進制的形式去打開,影響只是獲取到的內(nèi)容璃吧,和寫進去的內(nèi)容的數(shù)據(jù)類型楣导;
二進制文件只能以二進制的形式打開 (例如: 圖片、視頻畜挨、音頻等)
2.二進制數(shù)據(jù)
一般二進制數(shù)據(jù)都是通過網(wǎng)絡(luò)請求獲取到筒繁,或者通過讀取本地的二進制文件來取到
1)將字符串轉(zhuǎn)換二進制
bytes(字符串, 編碼方式)
字符串.encode(編碼方式)
2)將二進制轉(zhuǎn)換成字符串
str(二進制數(shù)據(jù), 編碼方式)
二進制數(shù)據(jù).decode(編碼方式)
3.文件上下文
with open(文件路徑,打開方式,編碼方式) as 文件對象:
操作文件
文件操作完成后,會自動關(guān)閉
def main():
with open('./files/test.txt', 'r', encoding='utf-8') as f1:
print(f1.read())
# 1. 普通文本文件以二進制的形式打開
f = open('./files/test.txt', 'rb')
reslut = f.read()
print(reslut, type(reslut))
f = open('./files/test.txt', 'wb')
f.write(bytes('bbb', encoding='utf-8'))
# 2. 二進制文件
f1 = open('./files/luffy4.jpg', 'rb')
reslut = f1.read()
print(reslut, type(reslut))
f2 = open('./files/aaa.jpg', 'wb')
f2.write(reslut)
if __name__ == '__main__':
main()
import json
1.json數(shù)據(jù)
1)滿足json格式的數(shù)據(jù)就叫json數(shù)據(jù)
2)json格式: 一個json有且只有一個數(shù)據(jù)巴元,這個數(shù)據(jù)必須滿足是json支持的數(shù)據(jù)類型
3)json支持的數(shù)據(jù)類型:
數(shù)字(number) - 包含所有的數(shù)字(整數(shù)和小數(shù))毡咏,支持科學(xué)計數(shù)法,例如:100, 12.8, 3e4
字符串(string) - 用雙引號括起來的字符集,字符也可以是轉(zhuǎn)義字符和編碼字符逮刨,
例如: "abc", "你好", "12334"呕缭,"abc\n123", "\u4e01abc"
布爾(bool) - true/false
數(shù)組(array) - 相當(dāng)于python中的列表,[100, "abc", true, [1, 2, 3]]
字典(dictionary) - 相當(dāng)于python中的字典, {"a":10, "b":56, "c":true}
空值 - null, 相當(dāng)于None
2.使用json
- 1)解析json數(shù)據(jù)(獲取到j(luò)son數(shù)據(jù)后將json中想要的東西解析出來) -- 做前端開發(fā)人員的工作
- 2)構(gòu)造json數(shù)據(jù)
在python中有一個內(nèi)置庫,專門負(fù)責(zé)json數(shù)據(jù)的處理: json庫
1.1) 將json數(shù)據(jù)轉(zhuǎn)換成python數(shù)據(jù)
json數(shù)據(jù) python數(shù)據(jù)
number int/float
string str, 可能會出現(xiàn)將雙引號變成單引號
boolean bool, true -> True; false -> False
array list
dictionary dict
空 null -> None
1.2)loads方法
json.loads(字符串, encoding='utf-8') - 解析json數(shù)據(jù),返回json對應(yīng)的python數(shù)據(jù)
字符串要求:字符串中內(nèi)容本身就是一個json數(shù)據(jù)(去掉引號后恢总,本身就是一個json數(shù)據(jù))
==================1.json轉(zhuǎn)python(json數(shù)據(jù)解析)=================
result = json.loads('"abc"', encoding='utf-8')
print(result, type(result))
result = json.loads('100.12', encoding='utf-8')
print(result, type(result))
result = json.loads('true', encoding='utf-8')
print(result, type(result))
result = json.loads('[10, 23, "yuting", true]', encoding='utf-8')
print(result, type(result))
result = json.loads('{"a": 100, "b": false}', encoding='utf-8')
print(result, type(result))
with open('./jsonData.json', 'r', encoding='utf-8') as f:
content = f.read()
# print(type(content), content)
content_py = json.loads(content, encoding='utf-8')
# print(type(content_py),content_py)
data = content_py['data']
# print(type(data), data)
# for dict1 in data:
# print(dict1['name'])
max_dict = max(data, key=lambda x: int(x['favourite']))
print(max_dict['name'], max_dict['text'], max_dict['favourite'])
====================2.python數(shù)據(jù)轉(zhuǎn)換json====================
2.1)python轉(zhuǎn)json
python數(shù)據(jù) json數(shù)據(jù)
int/float number
bool boolean,True --> true, False --> false
str string, 將單引號變成雙引號
list迎罗、tuple array
dict dictionary
空值 None -> null
2.2)
json.dumps(python數(shù)據(jù)) --> 將python數(shù)據(jù)轉(zhuǎn)換成內(nèi)容是對應(yīng)的json數(shù)據(jù)的字符串, 結(jié)果是一個字符串片仿!
result = json.dumps(100)
print(type(result), result)
result = json.dumps('abc')
print(type(result), result) # '"abc"'
result = json.dumps(True)
print(type(result), result) # 'true'
result = json.dumps([12, 'abc', [1, 2], True])
print(type(result), result) # '[12, "abc", [1, 2], true]'
result = json.dumps((12, True, 'abc', (1, 2)))
print(type(result), result) # '[12, true, "abc", [1, 2]]'
# result = json.dumps({12, 34, 5})
# print(type(result), result) # TypeError: Object of type 'set' is not JSON serializable
result = json.dumps({'name': '小明', 'age': 18})
print(type(result), result) # {"name": "\u5c0f\u660e", "age": 18}
====================3.json文件操作(了解)=====================
json.load(文件對象) - 將文件對象中文件的內(nèi)容轉(zhuǎn)換成python數(shù)據(jù)
文件的內(nèi)容只能是json數(shù)據(jù)(文件后綴沒有要求)
json.dump(python數(shù)據(jù)纹安,文件對象) -- 將python數(shù)據(jù)轉(zhuǎn)換成json字符串再寫入指定文件中
with open('./files/test.txt', 'r', encoding='utf-8') as f:
result = json.load(f)
# result = json.loads(f.read(), encoding='utf-8')
print(type(result), result)
with open('./test2.json', 'w', encoding='utf-8') as f:
json.dump([100, True, 'abc'], f)
# result = json.dumps([100, True, 'abc', None])
# f.write(result)
import json
1.數(shù)據(jù)怎么本地化?
數(shù)據(jù)保存在本地文件中一份
每次需要用到這個數(shù)據(jù)的時候,不是直接給值滋戳,而是從本地文件中讀取它的值
數(shù)據(jù)修改完后钻蔑,要將最新的數(shù)據(jù)保存到本地文件中2.什么時候需要用到j(luò)son文件
需要持久化的數(shù)據(jù)是字典、列表奸鸯、元祖
練習(xí)1: 每次運行程序的時候咪笑,打印當(dāng)前是第幾次運行這個程序
with open('./files/test.txt', 'r', encoding='utf-8') as f:
num = int(f.read())
num += 1
print(num)
with open('./files/test.txt', 'w', encoding='utf-8') as f:
f.write(str(num))
練習(xí)2: 實現(xiàn)添加學(xué)生的功能,要求娄涩,之前添加的學(xué)生要一直存在
with open('./files/students.txt', 'r', encoding='utf-8') as f:
# students = json.loads(f.read())
students = json.load(f)
def add_student():
name = input('姓名:')
age = input('年齡:')
stu = {'name': name, 'age':int(age)}
students.append(stu)
add_student()
add_student()
with open('./files/students.txt', 'w', encoding='utf-8') as f:
json.dump(students, f)
# f.write(json.dumps(students))
print(students)
def main():
pass
if __name__ == '__main__':
main()