1.write

# (1)
f = open('test.txt','w')
f.write('test')
f.close()

# (2)
with open('test.txt','w') as f:
    f.write('test')

# (1)(2)兩種方式是一樣的,只是用 with 寫法可以不用自己寫 f.close(),若沒有 f.close(),作業系統通常不會直接把資料寫入檔案,
# 而是先緩存在 memory 裡,等有空再慢慢寫入,所以一定要記得關掉 i/o ,避免寫入的內容不完整
# 參數是 'w' 的時候,每次寫入檔案都會覆蓋掉原有內容,因此可改用 'a' 讓新增的內容疊加下去
# 參數也可設為 'wb' 以此來寫入二進位的檔案內容

# 順便連json也介紹一下
import json
data = {'test':1}

# w+代表如果檔案不存在時,會以write模式建立檔案
with open('test.json','w+') as f:
    # dump是把python dict寫成json檔案
    json.dump(data, f)

# json.loads會把json string轉換成python dict 
d = json.loads('{"test":1,"age":2}')
print(d['test']) #可以使用操作python dict的方式取值

# json.dumps會把python dict轉換成json string
i = json.dumps({'test':'1','age':1})
print(type(i)) # 型別是str

2.read

with open('test.txt','r') as f:
    d = f.read()
    print(d)

# 但使用read()方法要小心,因為若檔案太大超過 memory size,就爆炸了,所以若不確定檔案是否會太大可使用 read(size)
# 並且使用迴圈不斷呼叫 read(size)
# 也可使用 readlines() 方法,讀取所有內容並依照行數存成一個 list (較適用在讀取組態文件)
# 讀取的參數 'r' 若改為 'rb' 可讀取二進位的內容,例如圖片或影像

# python 預設都是讀取 utf-8 編碼的檔案,若是其他編碼的話要傳入 encoding 參數,並指定編碼格式
f = open('test.txt', 'r', encoding='ascii')
# 如果遇到編碼不規則的話,通常會遇到 UnicodeDecodeError ,可再傳入另一個參數 errors ,代表遇到錯誤編碼該如何處理
f = open('test.txt', 'r', encoding='ascii', errors='ignore') # 最簡單就是直接忽略


# 如果是要讀json檔案
with open('test.json','r') as f:
    d = json.load(f) # 把json檔案parse成python dict
    print(d)

3.常見問題

import json
with open('test.json','r') as f:
    d = json.load(f)
    print(d)
>>> JSONDecodeError: Expecting value: line 1 column 1 (char 0)
# 出現這個錯代表檔案內容有問題,{'test':1}在json檔案裡不算json格式,{"test":1},用雙引號才是,所以要去檔案來源檢查一下

4.parse JSON to CSV

data = '{"test":[{"name": "josh", "email": "[email protected]"},{"name": "andy", "email": "[email protected]"},..]}'

import json
import csv

data_parsed = json.loads(data)
personal_data = data_parsed ['test']

# open a file for writing
with open('personal.csv', 'w') as csv_data:
    # create the csv writer object
    csvwriter = csv.writer(csv_data)
    count = 0

    for per in personal_data:
        if count == 0:
            header = per.keys()
            csvwriter.writerow(header)
            count += 1
        csvwriter.writerow(per.values())

results matching ""

    No results matching ""