python读写txt、csv、json
先写这些,有时间再加。
import csv
''' Description:文件读写工具 Author:西兰 Date:2019-11-30 '''
class util(object):
''' 以追加形式写入txt文件,带换行 '''
def write_to_txt(self,filename, line):
with open(filename, 'a', encoding='utf-8') as f:
f.write(line +'\n')
''' 读取txt文档,适合文本内容较小的文档 读取结果存入list,内存占用较大 :return list '''
def read_txt(self,filename):
with open(filename, 'r', encoding='utf-8') as f:
list = f.readlines()
return list
''' 读取txt文档,适合文本内容较大的文本,内容占用较小 '''
def read_txt_with_small_cache(self, filename):
with open(filename, 'r', encoding='utf-8')as f:
line = f.readline()
while(line):
print(line)
line = f.readline()
''' 写入csv,追加形式 row_data是列表形式 '''
def write_to_csv(self,filename,row_data):
with open(filename, 'a+', newline="", encoding='utf-8') as f:
csv_add = csv.writer(f)
csv_add.writerow(row_data)
''' 读取csv '''
def read_csv(self,filename):
with open(filename, newline='', encoding='UTF-8') as f:
rows = csv.reader(f)
for row in rows:
print(''.join(row))
##python读写json:
import json
''' 将数据保存为json格式 1、python3里面默认编码是unicode 2、做dump与dumps操作时,会默认将中文转换为unicode,但在做逆向操作load和loads时会转换为中文, 但是中间态(例如存储的json文件)的中文编码方式仍然是unicode 解决办法: 在dump里面添加ensure_ascii=False '''
dict = {}
data_dict = {}
dict['token'] = 'md5(gateguard+服务器IP)'
list = []
list.append(data_dict)
dict['data'] = list
data_dict['name'] = '张三'
data_dict['age'] = '24'
data_dict['address'] = '上海市松江区'
#写入json
with open('./data.json', mode='w', encoding='utf-8') as f:
f.write(json.dumps(dict, ensure_ascii=False, indent=2))
#读取json
with open('./data.json', mode='r', encoding='utf-8') as f2:
print(json.load(f2))
写入后的结果:
{
"token": "md5(gateguard+服务器IP)",
"data": [
{
"name": "张三",
"age": "24",
"address": "上海市松江区"
}
]
}
上海今天下起了小雨,呜啦啦~