python常见数据存储 csv txt pickle
生活随笔
收集整理的這篇文章主要介紹了
python常见数据存储 csv txt pickle
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.csv文件
(1)寫入
import csvwith 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 pdfiler = 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] # SourceTarget = df.loc[index].values[1] # TargetWeight = df.loc[index].values[2] # Weightprint(Source, Target, Weight)with open('XXX.csv', 'w') as wf :
等價于
open('XXX.csv', 'w')
close()
所以上面代碼可以寫成
import pandas as pdwith 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] # SourceTarget = df.loc[index].values[1] # TargetWeight = df.loc[index].values[2] # Weightprint(Source, Target, Weight)2.txt文件
讀出
file = open('1.txt', 'r')while True:line = file.readline()if line == '':breakprint(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 pickleresult = [1.0, 2, 3, 4, 5] with open('temp.pkl', 'wb') as file:pickle.dump(result, file)讀出
import picklewith open('temp.pkl', 'rb') as file:result = pickle.load(file)print(result)但是值得注意的是這種數據結構很容易被損害,尤其是你把'rb'寫成'wb'的時候,會導致文件徹底損壞,所以只使用之前先保存一下。
轉載于:https://www.cnblogs.com/JCcodeblgos/p/10126559.html
總結
以上是生活随笔為你收集整理的python常见数据存储 csv txt pickle的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 病毒分析基础(一)
- 下一篇: Python开发以太坊智能合约指南(we