Python学习之路(16)总结各种文件的读取和写入方法

茴香豆 Lv5

每次需要读取csv,json或者txt等类型文件时,总是要去google一下,所以在这里整理一下常用文件的读写,方便后续使用。

csv文件

python官方文档中有csv库的详细解析,具体参考:csv — CSV 文件读写 — Python 3.11.2 文档

使用Python I/O

使用python I/O方法进行读取时即是新建一个List 列表然后按照先行后列的顺序(类似C语言中的二维数组)将数据存进空的List对象中,如果需要将其转化为numpy数组也可以使用np.array(List name)进行对象之间的转化。

读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import csv

birth_data = []
birth_header = []
birth_weight_file = 'c:/file.csv' # 文件地址
with open(birth_weight_file) as csvfile:
csv_reader = csv.reader(csvfile) # 使用csv.reader读取csvfile中的文件
birth_header = next(csv_reader) # 读取第一行每一列的标题
for row in csv_reader: # 将csv 文件中的数据保存到birth_data中
birth_data.append(row)

birth_data = [[float(x) for x in row] for row in birth_data] # 将数据从string形式转换为float形式

birth_data = np.array(birth_data) # 将list数组转化成array数组便于查看数据结构
birth_header = np.array(birth_header)
print(birth_data.shape)
print(birth_header.shape)
# 打印数据和数据头的形状
# (189, 9)
# (9,)
data = torch.FloatTensor(birth_data) # 将numpy格式转换为tensor,使其可以使用pytorch相关运算

写入文件

1
2
3
4
with open("test.csv","w") as csvfile: 
writer = csv.writer(csvfile)
writer.writerow(["index","a_name","b_name"]) # 先写入columns_name
writer.writerows([[0,1,3],[1,2,3],[2,3,4]]) # 写入多行用writerows

使用Pandas

读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import pandas as pd

csv_data = pd.read_csv('birth_weight.csv') # 读取训练数据
print(csv_data.shape) # (189, 9)
N = 5
csv_batch_data = csv_data.tail(N) # 取后5条数据
print(csv_batch_data.shape) # (5, 9)
train_batch_data = csv_batch_data[list(range(3, 6))] # 取这20条数据的3到5列值(索引从0开始)
print(train_batch_data)
# RACE SMOKE PTL
# 184 0.0 0.0 0.0
# 185 0.0 0.0 1.0
# 186 0.0 1.0 0.0
# 187 0.0 0.0 0.0
# 188 0.0 0.0 1.0

写入文件

1
2
3
4
5
6
7
8
# 任意的多组列表
a = [1,2,3]
b = [4,5,6]
# 字典中的key值即为csv中列名
dataframe = pd.DataFrame({'a_name':a,'b_name':b})

#将DataFrame存储为csv,index表示是否显示行名,default=True
dataframe.to_csv("test.csv",index=False,sep=',')

JSON文件

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。JSON在python中分别由list和dict组成。JSON模块提供了四个功能:dumps、dump、loads、load。

dumps

dumps将python中的字典转换为字符串

1
2
3
4
5
6
7
8
9
import json

test_dict = {'bigberg': [7600, {1: [['iPhone', 6300], ['Bike', 800], ['shirt', 300]]}]}
print(test_dict)
print(type(test_dict)) # dict
#dumps 将数据转换成字符串
json_str = json.dumps(test_dict)
print(json_str)
print(type(json_str)) # str

loads

loads将字符串转换为字典

1
2
3
new_dict = json.loads(json_str)
print(new_dict)
print(type(new_dict)) # dict

dump

dump将数据写入json文件中。

1
2
with open("record.json","w") as f:
json.dump(new_dict,f)

load

load把文件打开,并把字符串变换为数据类型。

1
2
3
4
5
6
7
8
with open("record.json",'r') as load_f:
load_dict = json.load(load_f)
print(load_dict)
load_dict['smallberg'] = [8200,{1:[['Python',81],['shirt',300]]}]
print(load_dict)

with open("record.json","w") as dump_f:
json.dump(load_dict,dump_f)

TXT文件

Python学习之路(10)文件和异常 - 顺利毕业企划 (hxiangdou.github.io)

  • Title: Python学习之路(16)总结各种文件的读取和写入方法
  • Author: 茴香豆
  • Created at : 2023-02-14 22:16:15
  • Updated at : 2023-02-14 22:48:38
  • Link: https://hxiangdou.github.io/2023/02/14/Python_16/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
Python学习之路(16)总结各种文件的读取和写入方法