11.Python檔案讀寫操作
阿新 • • 發佈:2021-01-16
11.1 Python檔案讀寫
- open()函式
- 檔案的讀取與寫入
11.2 Python讀寫文字檔案
- 檔案寫入
- 檔案讀取
- 格式化的輸入輸出,使用%來格式化字串
11.3 Python讀寫二進位制檔案
- 預設都是讀取文字檔案,並且是ASCII編碼的文字檔案。 要讀取二進位制檔案,比如圖片、視訊等等,用’rb’模式開啟檔案即可。
- 要讀取非ASCII編碼的文字檔案,就必須以二進位制模式開啟,再解碼。 比如GBK編碼的檔案。
11.4 Python讀寫json檔案
json檔案格式一般有兩種:
- 第一種:每行一個json類似於以下這種形式:這種json格式是每一行是一個json,行與行之間沒有關聯。
- 第二種:一個檔案寫成一個大的json:這種格式每條記錄之間用,連線。
- 讀取json檔案,利用json.load函式
11.5 實驗
11.5.1文字
11.5.1.1寫資料
In:
# wf = open("output.txt",'w',encoding='utf-8')
In:
txt = '''
我來到山西五臺山
我來到北京天安門'''
In:
txt2 = '''
I am here'''
In:
wf.write(txt2)
out:
10
In:
# wf.close
out:
<function TextIOWrapper.close()>
In:
txt2
out:
'\nI am here'
In:
#自動關閉
with open("output2.txt",'w',encoding='utf-8') as f:
f.write(txt2)
In:
txt
out:
'\n我來到山西五臺山\n我來到北京天安門'
In:
with open("output.txt",'w',encoding='utf-8') as f:
f.write(txt)
11.5.1.2 讀資料
In:
with open("output.txt","r" ,encoding='utf-8') as f:
rtxt = f.read()
In:
type(rtxt)
out:
str
In:
rtxt.splitlines()
out:
['', '我來到山西五臺山', '我來到北京天安門']
In:
with open("output.txt","r",encoding='utf-8') as f:
rtxts = f.readlines()
In:
type(rtxts)
out:
list
In:
for txt in rtxts:
# print(txt)
print(txt.strip())
out:
我來到山西五臺山
我來到北京天安門
In:
newlist = [txt.strip() for txt in rtxts if len(txt.strip()) > 0]
newlist
out:
['我來到山西五臺山', '我來到北京天安門']
11.5.2 JSON
In:
import json
In:
#讀取用 json.loads
with open("poetry_10316.json",'r',encoding='utf-8') as f:
fred = f.read()
In:
poe = json.loads(fred)
In:
poe['name']
out:
'留上李右相(一作奉贈李右相林甫)'
In:
[key for key in poe.keys()]
out:
['id', 'star', 'name', 'dynasty', 'content', 'poet', 'tags']
In:
lis1 = []
for i in range(10):
dic1 = {}
dic1['id'] = i
dic1['name'] = 'sz'
lis1.append(dic1)
lis1
out:
[{'id': 0, 'name': 'sz'},
{'id': 1, 'name': 'sz'},
{'id': 2, 'name': 'sz'},
{'id': 3, 'name': 'sz'},
{'id': 4, 'name': 'sz'},
{'id': 5, 'name': 'sz'},
{'id': 6, 'name': 'sz'},
{'id': 7, 'name': 'sz'},
{'id': 8, 'name': 'sz'},
{'id': 9, 'name': 'sz'}]
In:
with open("output.json","w",encoding='utf-8') as f:
f.write(json.dumps(lis1))