python常見資料儲存 csv txt pickle
阿新 • • 發佈:2018-12-16
1.csv檔案
(1)寫入
import csv with open('test.csv', 'w', newline='', encoding='utf-8') as wf: # 用csv檔案包裝 writer = csv.writer(wf) # 建立標頭檔案 headers = ['Source', 'Target', 'Weight'] writer.writerow(headers) # 寫入資料 lists = ['a', 'b', 'c'] writer.writerow(lists) writer.writerow(['a', 'b', 'c']) writer.writerow(['a', 'b', 'c']) writer.writerow(['a', 'b', 'c']) # 一共寫入4行資料 # newline='' 每一行的資料沒有多餘的空格 # encoding='utf-8' 檔案編碼格式是'utf-8'
(2)讀取
import pandas as pd filer = open('test.csv', encoding='utf-8') df = pd.read_csv(filer) filer.close() # 按行遍歷csv檔案 for index in df.index: Source = df.loc[index].values[0] # Source Target = df.loc[index].values[1] # Target Weight = df.loc[index].values[2] # Weight print(Source, Target, Weight)
with open('XXX.csv', 'w') as wf :
等價於
open('XXX.csv', 'w')
close()
所以上面程式碼可以寫成
import pandas as pd with open('test.csv', 'r', encoding='utf-8') as rf: df = pd.read_csv(rf) # 按行遍歷csv檔案 for index in df.index: Source = df.loc[index].values[0] # Source Target = df.loc[index].values[1] # Target Weight = df.loc[index].values[2] # Weight print(Source, Target, Weight)
2.txt檔案
讀出
file = open('1.txt', 'r')
while True:
line = file.readline()
if line == '':
break
print(line)
寫入
fw = open('t2.txt', 'w')
fw.write('hello boy!')
fw.write('hello boy!')
fw.write('hello boy!')
fw.write('hello boy!\n')
fw.write('hello boy!')
3.pickle檔案
讀取資料速度快
寫入
import pickle
result = [1.0, 2, 3, 4, 5]
with open('temp.pkl', 'wb') as file:
pickle.dump(result, file)
讀出
import pickle
with open('temp.pkl', 'rb') as file:
result = pickle.load(file)
print(result)
但是值得注意的是這種資料結構很容易被損害,尤其是你把'rb'寫成'wb'的時候,會導致檔案徹底損壞,所以只使用之前先儲存一下。