Python学习之路(16)总结各种文件的读取和写入方法
每次需要读取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) birth_header = next(csv_reader) for row in csv_reader: birth_data.append(row)
birth_data = [[float(x) for x in row] for row in birth_data]
birth_data = np.array(birth_data) birth_header = np.array(birth_header) print(birth_data.shape) print(birth_header.shape)
data = torch.FloatTensor(birth_data)
|
写入文件
1 2 3 4
| with open("test.csv","w") as csvfile: writer = csv.writer(csvfile) writer.writerow(["index","a_name","b_name"]) writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
|
使用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) N = 5 csv_batch_data = csv_data.tail(N) print(csv_batch_data.shape) train_batch_data = csv_batch_data[list(range(3, 6))] print(train_batch_data)
|
写入文件
1 2 3 4 5 6 7 8
| a = [1,2,3] b = [4,5,6]
dataframe = pd.DataFrame({'a_name':a,'b_name':b})
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))
json_str = json.dumps(test_dict) print(json_str) print(type(json_str))
|
loads
loads将字符串转换为字典。
1 2 3
| new_dict = json.loads(json_str) print(new_dict) print(type(new_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)