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'的时候,会导致文件彻底损坏,所以只使用之前先保存一下。

猜你喜欢

转载自www.cnblogs.com/JCcodeblgos/p/10126559.html