轉載請代表出處:http://www.javashuo.com/article/p-sursppms-hu.htmlhtml
前提:文中例子介紹test.json內容:python
hello
咱們
326342
1.文件讀取json
(1)打開文件open,默認是已讀模式打開文件app
f = open('../dataconfig/test.json') print(f.read())
f.close() 輸出結果: hello 鎴戜滑 326342
read():一次性讀取文件全部內容函數
輸出結果中出現亂碼:須要給open函數傳入encoding參數spa
f = open('../dataconfig/test.json',encoding='utf-8') print(f.read())
f.close() 輸出結果: hello 咱們 326342
(2)read(size):讀取部分數據操作系統
f = open('../dataconfig/test.json',encoding='utf-8') print(f.read(3))
f.close()
輸出結果: hel
(3)redline():每次讀取一行數據,逐行讀取文件內容code
f = open('../dataconfig/test.json',encoding='utf-8') data = f.readline() while data: print(data) data = f.readline() f.close() 輸出結果: hello 咱們 326342
輸出結果中每一行數據讀取以後都會空一行,解決方案:print(data.strip())或者print(data,end='')htm
(4)readlines():讀取文件全部行對象
f = open('../dataconfig/test.json',encoding='utf-8') data = f.readlines() print(data) print(type(data)) for line in data: print(line.strip()) f.close() 輸出結果: ['hello\n', '咱們\n', '326342'] <class 'list'> hello 咱們 326342
(5)linecache.getline():讀取某個特定行數據
import linecache data = linecache.getline('../dataconfig/test.json',1) print(data) 輸出結果: hello
總結:不一樣場景下讀取方式選擇
f = open('../dataconfig/test.json','w') f.write('hello,world!') f.close()
test.json文件內容:hello,world!
(2)‘’a’就是appendin:一種寫入模式,寫入的內容不會覆蓋以前的內容,而是添加到文件中
f = open('../dataconfig/test.json','a') f.write('hello,world!') f.close()
test.json文件內容:
hello
咱們
326342hello,world!
3.上述讀寫文件例子看出,每次讀寫完以後,都要f.close()關閉文件,由於文件對象會佔用操做系統的資源,而且操做系統同一時間能打開的文件數量也是有限的。
可是實際中,文件讀寫可能產生IOError,一旦出錯,後面的f.close()就不會調用。因此,爲了保證任什麼時候候都能關閉文件,可使用try-finally來實現(finally內的代碼無論有無異常發生,都會執行)
try: f = open('../dataconfig/test.json', 'r') print(f.read()) finally: if f: f.close()
每次都這樣寫實在是麻煩,python中的with語句用法能夠實現
with open('../dataconfig/test.json',encoding='utf-8') as f: print(f.read()) 輸出結果: hello 咱們 326342
打開多個文件進行操做:
with open('../dataconfig/test.json',encoding='utf-8') as f1,open('../dataconfig/test1.json',encoding='utf-8') as f2,open('../dataconfig/test2.json',encoding='utf-8') as f3: for i in f1: j = f2.readline() k = f3.readline() print(i.strip(),j.strip(),k.strip())