os庫提供了很多和文件管理操作
- 數(shù)據(jù)本地化和數(shù)據(jù)持久化 - 通過文件將數(shù)據(jù)存到硬盤中
- 數(shù)據(jù)庫文件、txt、json、plist、xml、png文件、MP4、mp3等
文件操作 - 文件內容操作
- 基本步驟: 打開文件 --> 操作文件(讀/寫) --> 關閉文件
- 1.打開文件
"""
open(file, mode, encoding=None) - 以指定方式打開指定文件,并且返回被打開的文件對象
file -- 字符串,需要打開的文件的路徑
./ -- 當前文件所在目錄(./可以省略)
../ -- 當前文件所在目錄的上層目錄
mode -- 字符串,打開方式
r -- 默認值,以讀的方式打開文件(只能進行讀操作), 讀出來的是文本
w -- 以寫的方式打開文件(只能進行寫操作), 覆蓋
a -- 以寫的方式打開文件(只能進行寫操作), 追加
rb/br -- 以讀的方式打開文件(只能進行讀操作),讀出來的內容是二進制數(shù)據(jù)
wb/bw -- 以寫的方式打開文件(只能進行寫操作),將二進制數(shù)據(jù)寫入文件中
+ -- 以讀寫的方式打開(了解)
encoding -- 文本編碼方式
utf-8
注意:文本編碼只針對文本文件、二進制文件不能設置編碼方式
"""
- 2.文件操作
"""
文件對象.read() -- 從讀寫位置開始,讀到文件結尾,并且返回
(讀寫位置默認在文件開頭)
文件對象.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())
# 練習: 一行一行的將文件中的內容讀完
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(寫的內容) - 將指定內容寫入到指定文件中,返回被寫入的內容的長度
"""
f = open('./files/test.txt', 'w', encoding='utf-8')
result = f.write('abc')
print(result)
# 關閉文件
f.close()
# ==================================
"""
注意: 打開文件的時候,如果以讀的方式打開一個不存在的文件,會出現(xiàn)異常,報錯
如果以寫的方式打開一個不存在的文件,不會出現(xiàn)異常,并且會自動創(chuàng)建對應的文件再打開
"""
f1 = open('./files/test4.txt', 'w', encoding='utf-8')
二進制文件操作
"""
rb - 讀的時候獲取到的是二進制數(shù)據(jù)(bytes)
wb - 寫的時候寫入的內容要求類型是二進制文件
普通的文本文件可以通過二進制的形式去打開,影響只是獲取到的內容,和寫進去的內容的數(shù)據(jù)類型;
二進制文件只能以二進制的形式打開 (例如: 圖片、視頻、音頻等)
"""
二進制數(shù)據(jù)
"""
一般二進制數(shù)據(jù)都是通過網絡請求獲取到,或者通過讀取本地的二進制文件來取到
1)將字符串轉換二進制
bytes(字符串, 編碼方式)
字符串.encode(編碼方式)
2)將二進制轉換成字符串
str(二進制數(shù)據(jù), 編碼方式)
二進制數(shù)據(jù).decode(編碼方式)
"""
文件上下文
"""
with open(文件路徑,打開方式,編碼方式) as 文件對象:
操作文件
文件操作完成后,會自動關閉
"""
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)
socket
import socket
server = socket.socket()
server.bind(('10.7.190.127', 8080))
server.listen(512)
while True:
connect, addr = server.accept()
f = open('./files/luffy4.jpg', 'br')
data = f.read()
# message = input('請輸入:')
# connect.send(bytes(message, encoding='utf-8'))
# connect.send(message.encode('utf-8'))
connect.send(data)
import socket
client = socket.socket()
client.connect(('10.7.190.127', 8080))
# 創(chuàng)建空的二進制數(shù)據(jù)
data = bytes()
n = 0
while True:
n += 1
message = client.recv(1024)
print(len(message))
data += message
if len(message) < 1024:
break
# print(str(message, encoding='utf-8'))
# print(message.decode('utf-8'))
f = open('new.jpg', 'wb')
f.write(data)
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ù)),支持科學計數(shù)法,例如:100, 12.8, 3e4
字符串(string) - 用雙引號括起來的字符集,字符也可以是轉義字符和編碼字符,
例如: "abc", "你好", "12334","abc\n123", "\u4e01abc"
布爾(bool) - true/false
數(shù)組(array) - 相當于python中的列表,[100, "abc", true, [1, 2, 3]]
字典(dictionary) - 相當于python中的字典, {"a":10, "b":56, "c":true}
空值 - null, 相當于None
"""
使用json
- 解析json數(shù)據(jù)(獲取到json數(shù)據(jù)后將json中想要的東西解析出來) -- 做前端開發(fā)人員的工作
- 構造json數(shù)據(jù)
"""
在python中有一個內置庫,專門負責json數(shù)據(jù)的處理: json庫
1.1) 將json數(shù)據(jù)轉換成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對應的python數(shù)據(jù)
字符串要求:字符串中內容本身就是一個json數(shù)據(jù)(去掉引號后,本身就是一個json數(shù)據(jù))
"""
# ==================1.json轉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ù)轉換成json====================
"""
2.1)python轉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ù)轉換成內容是對應的json數(shù)據(jù)的字符串, 結果是一個字符串!
"""
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(文件對象) - 將文件對象中文件的內容轉換成python數(shù)據(jù)
文件的內容只能是json數(shù)據(jù)(文件后綴沒有要求)
json.dump(python數(shù)據(jù),文件對象) -- 將python數(shù)據(jù)轉換成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ù)保存在本地文件中一份
每次需要用到這個數(shù)據(jù)的時候,不是直接給值,而是從本地文件中讀取它的值
數(shù)據(jù)修改完后,要將最新的數(shù)據(jù)保存到本地文件中
2.什么時候需要用到json文件
需要持久化的數(shù)據(jù)是字典、列表、元祖
3.作業(yè): 登錄注冊系統(tǒng)
"""
# 練習1: 每次運行程序的時候,打印當前是第幾次運行這個程序
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))
# 練習2: 實現(xiàn)添加學生的功能,要求,之前添加的學生要一直存在
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