日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python常见数据存储 csv txt pickle

發(fā)布時(shí)間:2024/9/21 python 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python常见数据存储 csv txt pickle 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1.csv文件

(1)寫入

import csvwith open('test.csv', 'w', newline='', encoding='utf-8') as wf:# 用csv文件包裝writer = csv.writer(wf)# 創(chuàng)建頭文件headers = ['Source', 'Target', 'Weight']writer.writerow(headers)# 寫入數(shù)據(jù)lists = ['a', 'b', 'c']writer.writerow(lists)writer.writerow(['a', 'b', 'c'])writer.writerow(['a', 'b', 'c'])writer.writerow(['a', 'b', 'c'])# 一共寫入4行數(shù)據(jù)# newline='' 每一行的數(shù)據(jù)沒有多余的空格 # 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 :
等價(jià)于
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文件

讀取數(shù)據(jù)速度快

寫入

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)

但是值得注意的是這種數(shù)據(jù)結(jié)構(gòu)很容易被損害,尤其是你把'rb'寫成'wb'的時(shí)候,會(huì)導(dǎo)致文件徹底損壞,所以只使用之前先保存一下。

轉(zhuǎn)載于:https://www.cnblogs.com/JCcodeblgos/p/10126559.html

總結(jié)

以上是生活随笔為你收集整理的python常见数据存储 csv txt pickle的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。