os庫(kù)提供了很多和文件管理操作
1.數(shù)據(jù)本地化和數(shù)據(jù)持久化
通過文件將數(shù)據(jù)存到硬盤中
數(shù)據(jù)庫(kù)文件、txt、json、plist、xml、png文件、MP4、mp3等
2.文件操作 - 文件內(nèi)容操作
基本步驟: 打開文件 --> 操作文件(讀/寫) --> 關(guān)閉文件
1)打開文件
open(file, mode, encoding=None) - 以指定方式打開指定文件,并且返回被打開的文件對(duì)象
file -- 字符串,需要打開的文件的路徑
./ -- 當(dāng)前文件所在目錄(./可以省略)
../ -- 當(dāng)前文件所在目錄的上層目錄
mode -- 字符串,打開方式
r -- 默認(rèn)值,以讀的方式打開文件(只能進(jìn)行讀操作), 讀出來的是文本
w -- 以寫的方式打開文件(只能進(jìn)行寫操作), 覆蓋
a -- 以寫的方式打開文件(只能進(jìn)行寫操作), 追加
rb/br -- 以讀的方式打開文件(只能進(jìn)行讀操作),讀出來的內(nèi)容是二進(jìn)制數(shù)據(jù)
wb/bw -- 以寫的方式打開文件(只能進(jìn)行寫操作),將二進(jìn)制數(shù)據(jù)寫入文件中
+ -- 以讀寫的方式打開(了解)
encoding -- 文本編碼方式
utf-8
注意:文本編碼只針對(duì)文本文件、二進(jìn)制文件不能設(shè)置編碼方式
2)文件操作
文件對(duì)象.read() -- 從讀寫位置開始,讀到文件結(jié)尾,并且返回
(讀寫位置默認(rèn)在文件開頭)
文件對(duì)象.seek(字節(jié)數(shù)) -- 將讀寫位置移動(dòng)到指定的地方(了解)
1.文件讀操作
1)read
f = open('./files/test.txt', 'r', encoding='utf-8')
result = f.read()
print(result, type(result))
將讀寫位置移動(dòng)到文件開頭
f.seek(0)
result = f.read()
print('====:', result)
- 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.文件寫操作
文件對(duì)象.write(寫的內(nèi)容) - 將指定內(nèi)容寫入到指定文件中,返回被寫入的內(nèi)容的長(zhǎng)度
f = open('./files/test.txt', 'w', encoding='utf-8')
result = f.write('abc')
print(result)
3)關(guān)閉文件
f.close()
注意: 打開文件的時(shí)候,如果以讀的方式打開一個(gè)不存在的文件,會(huì)出現(xiàn)異常,報(bào)錯(cuò)
如果以寫的方式打開一個(gè)不存在的文件,不會(huì)出現(xiàn)異常,并且會(huì)自動(dòng)創(chuàng)建對(duì)應(yīng)的文件再打開
f1 = open('./files/test4.txt', 'w', encoding='utf-8')
3.二進(jìn)制文件操作
rb - 讀的時(shí)候獲取到的是二進(jìn)制數(shù)據(jù)(bytes)
wb - 寫的時(shí)候?qū)懭氲膬?nèi)容要求類型是二進(jìn)制文件
普通的文本文件可以通過二進(jìn)制的形式去打開,影響只是獲取到的內(nèi)容,和寫進(jìn)去的內(nèi)容的數(shù)據(jù)類型;
二進(jìn)制文件只能以二進(jìn)制的形式打開 (例如: 圖片、視頻、音頻等)
4.二進(jìn)制數(shù)據(jù)
一般二進(jìn)制數(shù)據(jù)都是通過網(wǎng)絡(luò)請(qǐng)求獲取到,或者通過讀取本地的二進(jìn)制文件來取到
1)將字符串轉(zhuǎn)換二進(jìn)制
bytes(字符串, 編碼方式)
字符串.encode(編碼方式)
2)將二進(jìn)制轉(zhuǎn)換成字符串
str(二進(jìn)制數(shù)據(jù), 編碼方式)
二進(jìn)制數(shù)據(jù).decode(編碼方式)
5.文件上下文
"""
with open(文件路徑,打開方式,編碼方式) as 文件對(duì)象:
操作文件
文件操作完成后,會(huì)自動(dòng)關(guān)閉
"""
```python
def main():
with open('./files/test.txt', 'r', encoding='utf-8') as f1:
print(f1.read())
# 1. 普通文本文件以二進(jìn)制的形式打開
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. 二進(jìn)制文件
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()
6.json數(shù)據(jù)
1)滿足json格式的數(shù)據(jù)就叫json數(shù)據(jù)
2)json格式: 一個(gè)json有且只有一個(gè)數(shù)據(jù),這個(gè)數(shù)據(jù)必須滿足是json支持的數(shù)據(jù)類型
3)json支持的數(shù)據(jù)類型:
數(shù)字(number) - 包含所有的數(shù)字(整數(shù)和小數(shù)),支持科學(xué)計(jì)數(shù)法,例如:100, 12.8, 3e4
字符串(string) - 用雙引號(hào)括起來的字符集,字符也可以是轉(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
1.使用json
1)解析json數(shù)據(jù)(獲取到j(luò)son數(shù)據(jù)后將json中想要的東西解析出來) -- 做前端開發(fā)人員的工作
2)構(gòu)造json數(shù)據(jù)
在python中有一個(gè)內(nèi)置庫(kù),專門負(fù)責(zé)json數(shù)據(jù)的處理: json庫(kù)
import json
1.1) 將json數(shù)據(jù)轉(zhuǎn)換成python數(shù)據(jù)
| json數(shù)據(jù) | python數(shù)據(jù) |
|---|---|
| number | int/float |
| string | str, 可能會(huì)出現(xiàn)將雙引號(hào)變成單引號(hào) |
| boolean | bool, true -> True; false -> False |
| array | list |
| dictionary | dict |
| 空 | null -> None |
1.2)loads方法
json.loads(字符串, encoding='utf-8') - 解析json數(shù)據(jù),返回json對(duì)應(yīng)的python數(shù)據(jù)
字符串要求:字符串中內(nèi)容本身就是一個(gè)json數(shù)據(jù)(去掉引號(hào)后,本身就是一個(gè)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, 將單引號(hào)變成雙引號(hào) |
| list、tuple | array |
| dict | dictionary |
| 空值 | None -> null |
2.2)
json.dumps(python數(shù)據(jù)) --> 將python數(shù)據(jù)轉(zhuǎn)換成內(nèi)容是對(duì)應(yīng)的json數(shù)據(jù)的字符串, 結(jié)果是一個(gè)字符串!
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(文件對(duì)象) - 將文件對(duì)象中文件的內(nèi)容轉(zhuǎn)換成python數(shù)據(jù)
文件的內(nèi)容只能是json數(shù)據(jù)(文件后綴沒有要求)
json.dump(python數(shù)據(jù),文件對(duì)象) -- 將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)
1.數(shù)據(jù)怎么本地化?
數(shù)據(jù)保存在本地文件中一份
每次需要用到這個(gè)數(shù)據(jù)的時(shí)候,不是直接給值,而是從本地文件中讀取它的值
數(shù)據(jù)修改完后,要將最新的數(shù)據(jù)保存到本地文件中
2.什么時(shí)候需要用到j(luò)son文件
需要持久化的數(shù)據(jù)是字典、列表、元祖
練習(xí)1: 每次運(yùn)行程序的時(shí)候,打印當(dāng)前是第幾次運(yùn)行這個(gè)程序
import json
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: 實(shí)現(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)