day14 文件操作

1.計算機數(shù)據(jù)的存儲

"""
計算機的存儲系統(tǒng)分為 運行內(nèi)存 和 硬盤 兩種:
運行內(nèi)存:用來保存程序運行過程中產(chǎn)生的數(shù)據(jù),程序運行結(jié)束后會自動銷毀
硬盤: 硬盤是用來保存文件的,保存在文件中的數(shù)據(jù)就是保存在硬盤中的。除非手動刪除,否則數(shù)據(jù)會一直存在
"""

2.數(shù)據(jù)持久化

"""
數(shù)據(jù)持久化就是講數(shù)據(jù)以各種形式保存到硬盤中(保存到本地文件中)
"""

3.文件操作

"""
文件操作基本步驟:打開文件 -> 操作文件(讀、寫) -> 關(guān)閉文件
"""

1)打開文件

"""
open(file, mode='r', encoding=None) - 以指定的模式打開指定文件并且返回一個文件對象

說明:
a. file - 文件路徑,字符串類型
絕對路徑:文件/文件夾的全路徑 (一般不寫絕對路徑)
相對路徑:只寫文件絕對路徑的一部分,另外一部分用特殊符號代替
./ - 表示當前目錄(當前寫代碼的文件所在的文件夾), 可以省略
../ - 表示當前目錄的上層目錄
.../ - - 表示當前目錄的上層目錄的上層目錄
..../
...../
"""

絕對路徑

open(r'/Users/yuting/授課/python2002/01語言基礎(chǔ)/day14-文件操作/files/text.txt')

相對路徑: ./

open('./files/text.txt')
open('./text2.txt')
open('files/text.txt')

相對路徑:../

open('../day14-文件操作/files/text.txt')

"""
b. mode - 打開方式,字符串類型
第一組:控制操作類型
r - 以只讀的方式打開文件(默認值)
w - 以只寫的方式打開文件(打開前會先清空原文件中的內(nèi)容)
a - 以只寫的方式打開文件;
第二組:控制數(shù)據(jù)類型(文本-str/二進制數(shù)據(jù)-bytes)
t - 操作的數(shù)據(jù)是文本數(shù)據(jù)(默認)
b - 操作的數(shù)據(jù)是二進制數(shù)據(jù)

        注意:每一組值只選一個,兩組值進行組合使用

"""

情況一:r、rt

f = open('files/text.txt', 'rt')

content = f.read()

# f.write('abc') # io.UnsupportedOperation: not writable

print(content)

print(type(content)) # <class 'str'>

情況二:rb

f = open('files/text.txt', 'rb')

content = f.read()

print(content)

print(type(content)) # <class 'bytes'>

情況三:wt

f = open('files/text.txt', 'w')

# f.read() # io.UnsupportedOperation: not readable

f.write('abc123')

情況四:at

f = open('files/text.txt', 'a')

# f.read() # io.UnsupportedOperation: not readable

f.write('你好嗎?')

情況五:wb

f = open('files/text.txt', 'wb')
f.write(b'how are you!') # TypeError: a bytes-like object is required, not 'str'
f.write(bytes('你好!', encoding='utf-8'))

"""
c. encoding - 文本編碼方式; 直接寫 'utf-8'
注意:如果打開方式中帶 b , 不能設(shè)置 encoding
"""

open('files/text.txt', 'rb', encoding='utf-8') # ValueError: binary mode doesn't take an encoding argument

f = open('files/text.txt', 'r', encoding='utf-8')
print(f.read())

總結(jié):文本文件打開的時候可以是 t 也可以是 b; 二進制文件只能是 b 打開(圖片文件、音視頻文件等)

f = open('files/image.jpg', 'rb')
f.read()

1.打開文件

"""
打開文件方式一:
文件對象 = open(文件路徑, 文件打開方式, encoding=文本編碼方式)
操作文件對象
文件對象.close()

with open(文件路徑, 文件打開方式, encoding=文本編碼方式) as 文件對象:
操作文件對象
"""
print('方式一:')
f = open('files/text.txt', encoding='utf-8')
print(f.read())
f.close()

print(f.read()) # ValueError: I/O operation on closed file.

print('方式二:')
with open('files/text.txt', encoding='utf-8') as f:
print(f.read())

print(f.read()) # ValueError: I/O operation on closed file.

print('===============================')

2.文件讀操作

"""
1)文件對象.read() - 從文件讀寫位置開始,讀到文件的結(jié)尾(默認情況下讀寫位置在文件開頭)
"""
with open('files/text.txt', 'r', encoding='utf-8') as f:
content = f.read()
print('第一次:', content)
content = f.read()
print('第二次:', content)

"""
2)文件對象.readline() - 讀文本文件的一行內(nèi)容(從當前讀寫位置讀到一行結(jié)束)
3)文件對象.readlines() - 一行一行的讀,讀完為止。返回的是一個列表,列表中的元素是每一行的內(nèi)容
"""
print('==============================')
with open('files/text.txt', encoding='utf-8') as f:
content = f.readline()
print(content)
content = f.readline()
print(content)

練習:一行一行的讀文件,讀完為止

def read_file(file):
with open(file, 'r', encoding='utf-8') as f:
while True:
c = f.readline()
if not c:
break
print(c)

print('========================')
read_file('files/text.txt')

3.寫操作

"""
文件對象.write(內(nèi)容)
"""
with open('files/text.txt', 'a', encoding='utf-8') as f:
f.write('\n春眠不覺曉')

1.數(shù)據(jù)持久化的基本操作

"""
a. 數(shù)據(jù)保存在文件中
b. 需要數(shù)據(jù)的時候從文件中去讀數(shù)據(jù)
c. 當數(shù)據(jù)發(fā)生改變的時候,對保存數(shù)據(jù)的文件進行更新
"""

注意:如果以讀的方式打開一個不存在的文件,程序會報錯!如果是以寫的方式打開一個不存在的文件,不會報錯并且會自動新建這個文件

open('files/text2.txt', 'r') # FileNotFoundError: [Errno 2] No such file or directory: 'files/text2.txt'

open('files/text4.txt', 'a')

練習:寫一個程序統(tǒng)計這個程序啟動的次數(shù)

with open('files/count', encoding='utf-8') as f:
count = int(f.read())
count += 1
print(count)
with open('files/count', 'w', encoding='utf-8') as f:
f.write(str(count))

思考:寫程序?qū)崿F(xiàn)添加學生的功能,要求每次運行程序添加的學生,下次還在

def add_student():
name = input('姓名:')
with open('files/students.txt', 'a', encoding='utf-8') as f:
f.write(name+' ')

with open('files/students.txt', encoding='utf-8') as f:
    print(f.read())

add_student()

students = ['張三', '小明', '小花']

students = [

{'name': '張三', 'age': 18, 'tel': '110'},

{'name': '小明', 'age': 20, 'tel': '120'},

{'name': '小花', 'age': 21, 'tel': '119'}

]

# 1.字典和列表的寫操作: 先將列表或者字典轉(zhuǎn)換成字符串

with open('files/students.txt', 'w', encoding='utf-8') as f:

f.write(str(students))

# 2.字典和列表的讀操作:將容器格式的字符串轉(zhuǎn)換成對應(yīng)的容器型數(shù)據(jù)類型(eval)

with open('files/students.txt', 'r', encoding='utf-8') as f:

content = f.read()

print(content)

print(type(content))

new_content = eval(content)

print(new_content)

print(type(new_content))

for item in new_content:

print(item)

print(type(item))

def add_student():
name = input('姓名:')
age = input('年齡:')
tel = input('電話:')
stu = {'name': name, 'age': age, 'tel': tel}
with open('files/students.txt', 'r', encoding='utf-8') as f:
all_students = eval(f.read())
all_students.append(stu)
with open('files/students.txt', 'w', encoding='utf-8') as f:
f.write(str(all_students))
print(all_students)

add_student()

import json

1.什么是json

"""
1)存在的意義
json就是不同編程語言之間進行數(shù)據(jù)交流的一種通用格式

2)概念
json是一種數(shù)據(jù)格式:a.一個json有且只有一個數(shù)據(jù) b.這個數(shù)據(jù)是json支持的數(shù)據(jù)類型的數(shù)據(jù)

3)json支持的數(shù)據(jù)類型: 數(shù)字類型、字符串、布爾、數(shù)組、字典/對象、null(空值)
a.數(shù)字類型: 所有的數(shù)字(19, 90, 802, -23,0.34,3e4)
b.字符串:用雙引號引起來的文本數(shù)據(jù)(支持轉(zhuǎn)義字符) - 必須是雙引號
c.布爾: 只有 true 和 false 兩個值
d.數(shù)組: 相當于python的列表, [元素1, 元素2, 元素3,...]
e.字典: 相當于Python的字典,{key1:value1, key2:value2,...}
注意:key只能是字符串
f.空值:null(相當于None)
"""

2.json轉(zhuǎn)python

"""
json python
數(shù)字類型 數(shù)字(int/float)
字符串 字符串(可能會將雙引號變成單引號)
布爾 布爾(true->True, false -> False)
數(shù)組 列表
字典 字典
空值 null -> None

json.loads(字符串) - 將json格式的字符串轉(zhuǎn)換成python對應(yīng)的數(shù)據(jù)。(這兒的字符串的內(nèi)容必須滿足json格式)
"""

json.loads('abc') # 報錯:json.decoder.JSONDecodeError

result = json.loads('"abc"')
print(type(result), result)

result = json.loads('true')
print(result)

result = json.loads('[100, "abc", true, null]')
print(result)

3.python轉(zhuǎn)json

"""
python json
int/float 數(shù)字
字符串 變成雙引號的字符串
布爾 布爾(True->true, False->false)
列表/元組 數(shù)組
字典 字典
None null

json.dumps(數(shù)據(jù)) - 將指定的python數(shù)據(jù)轉(zhuǎn)換成json格式的字符串
"""
result = json.dumps([100, 'abc', True, (10, 20), None])
print(type(result), result)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容