一些常用的文本文件格式(TXT,JSON,CSV)以及如何从这些文件中读取和写入数据

时间:2023-03-09 06:27:55
一些常用的文本文件格式(TXT,JSON,CSV)以及如何从这些文件中读取和写入数据

TXT文件

txt是微软在操作系统上附带的一种文本格式,文件以.txt为后缀。

从txt文件中读取数据:

with open ('xxx.txt') as file:
data=file.readlines()

将数据写入txt文件:

with open ('xxx.txt','a',encoding='utf-8') as file:
file.write('xxxx')

注:a表示append,将数据一行行写入文件


JSON文件

JSON指JavaScript对象表示法(JavaScript Object Notation),是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成,文件以.json为后缀。

JSON对象可以以字符串的形式储存在文件中(不一定是json文件)。

一些常见的JSON格式:

{"key1":"value1","key2":"value2"}   由多个key:value键值对组成
{"key":["a","b","sojson.com"]}      value是一个array的JSON格式

(注:JSON格式数据必须用双引号,错误的JSON格式:{'name':'imooc'})

读取以JSON格式储存的数据文件(JSON格式的数据被储存在其他格式的文件里):

1)使用json模块(首先import json)

with open ('xxx') as file:
data=json.loads(file.read())

从json文件中读取数据:

1)使用json模块(首先import json)

with open ('xxx.json') as file:
data=json.load(file)

2)使用pandas库(首先import pandas as pd)

data=pd.read_json(file_name,orient)

将数据写入json文件:

1)使用json模块(首先import json)

with open ('xxx.json','w') as file:
file.write(json.dumps("xxxx"))

如数据内有中文:

with open ('xxx.json','w',encoding='utf-8') as file:
file.write(json.dumps("xxxx",ensure_ascii=False))

注:json库的loads()方法将JSON格式的文本字符串转为JSON对象

json库的load()方法直接读取json文件

json库的dumps()方法将JSON对象转为文本字符串


CSV文件

CSV是一种通用的、相对简单的文件格式,称为逗号分隔值(Comma-Separated Values),有时也称为字符分隔值,因为分隔字符也可以不是逗号,文件以.csv为后缀。

从csv文件中读取数据:

1)使用csv模块(首先import csv)

with open ('xxx.csv',encoding='utf-8') as file:
data=csv.reader(file,delimiter=',')

2)使用pandas库(首先import pandas as pd)

data=pd.read_csv(file_name,sep=',')

将数据写入csv文件:

1)使用csv模块(首先import csv)

with open('xxx.csv','w') as file:
writer=csv.writer(file)
writer.writerow([xxxx])

2)使用pandas库(首先import pandas as pd)

data.to_csv(file_name,encoding='utf-8')