python常見數據存儲 csv txt pickle


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'的時候,會導致文件徹底損壞,所以只使用之前先保存一下。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM