Python-数据读取

txt/csv

导入numpy

同一行的数据都为浮点数,或者说是同一行的数据格式相同时:

 with open(input_file, 'r') as f:#打开文件
        header = f.readline().strip()#跳过一行
        column_names = header.split('|')# 以管道分隔符切分数据
        values = np.loadtxt(f, delimiter='|')

同一行的数据格式不相同时,比如字符串和浮点数结合时:

选择跳过某一列或者只读取某一列数据,下面为只读取某一列数据

with open(input_file, 'r') as f:#打开文件
     values = np.loadtxt(f,delimiter=' ',dtype=int,usecols = (3))#读取第4列 分隔符为空格

excel( .xlsx)

读取:导入pandas

#input_template路径+文件名 
df_input_Analyze = pd.read_excel(input_template, encoding='gb18030').dropna(axis=1, how='all')

 写入

"""
函数说明:保存数据为excel
   .xlsx

Parameters:
    table_dict - 字典类型 key-DatFrame(表)
    keyword  -  最终输出的excel的文件名
Returns:
Author:
    heda3
Blog:
    https://blog.csdn.net/heda3
Modify:
    2019-10-12
"""
        def generate_excel(table_dict, keyword):
            with pd.ExcelWriter(keyword+'.xlsx') as writer:
                for sheet_name in table_dict:#读取每一个DataFrame
                    table_dict[sheet_name].to_excel(writer, sheet_name=sheet_name, index=None)

JSON

JSON: JavaScript Object Notation(JavaScript 对象表示法)

JSON 是存储和交换文本信息的语法

 导入 Json   模块,它提供了四个方法: dumps、dump、loads、load

dumps : 把数据类型转换成字符串 
dump : 把数据类型转换成字符串并存储在文件中 
loads : 把字符串转换成数据类型 
load : 把文件打开从字符串转换成数据类型

读取

import json
#open 默认为只读 r 以什么样的编码方式打开
#设置以utf-8解码模式读取文件,encoding参数必须设置,否则默认以gbk模式读取文件,当文件中包含中文时,会报错
with open("D:\Python Example\Tianyancha\xx.json",'r', encoding='utf-8') as load_f:
    load_dict = json.load(load_f)
    print(load_dict)

或者:

import json
#读取Json文件加载为python对象
f = open("D:\Python Example\Tianyancha\xx.json", encoding='utf-8')
bb=json.load(f)

注意的是读取文件使用的函数是:json.load(),从内存中读取使用的函数是:json.loads()

参考:json中load和loads区别 https://www.cnblogs.com/bigtreei/p/10466518.html

写入

## 测试JSON格式数据的保存和读取
import json
import codecs#编码解码模块
import time
import re
import pandas as pd
from collections import OrderedDict


class WriterJson:
    def __init__(self):
        pass

    # 将单个DataFrame保存为JSON,确保中文显示正确
    def df_to_json(self, df, orient:str = 'table'):
        return json.loads(df.to_json(orient, force_ascii=False))

    # 将多个DataFrames组成的字典批量保存为JSON,确保中文显示正确:服务于类似`金融产品信息表`这样的包含多
    def dfs_to_json(self, dic_dfs, orient:str = 'table'):
        pass

    # 将单个OrderedDict:key-DataFrame保存为JSON List
    def odict_to_json(self, odict):
        items = list(odict.items())#items[i][0] key   items[i][1]  value
        list_JSONed = []

        # 把列表中的每个df通过list append变成json
        for i in range(len(items)):
            try:
                #to_json为pandas自带的pandas.DataFrame.to_json 可参考https://blog.csdn.net/huanbia/article/details/72674832
                 #其中的items[i][1].to_json(orient='table', force_ascii=False) 转换为Json的str模式
                 #json.loads 将包含一个 JSON 文档的文件反序化为Python对象
                list_JSONed.append([items[i][0],json.loads(items[i][1].to_json(orient='table', force_ascii=False))])
            except:
                print(items[i][0] + '表为空,请检查。')
        # 记录版本信息 dict嵌套在list之中
        list_JSONed.append({'version_date': time.strftime("%Y/%m/%d")})

        return list_JSONed

    # 从list_JSONed获取公司名称,用于设置JSON文件名称
    def get_company_name_from_JSON(self, items_JSONed):
        pass

    # 将一个json list或者json dict存入文件
    def write_json(self, json_list, file_name, indent=4, encoding='utf-8'):
        f_out = codecs.open(file_name, 'w', encoding=encoding)#以utf-8 打开一个文件
        #json格式的文件转换为str /将 obj 序列化为 JSON 格式的 str  indent:表示缩进 使用一个正整数会让每一层缩进同样数量的空格
          #ensure_ascii=False 字符原样输出
        json_str = json.dumps(json_list, indent=indent, ensure_ascii=False) #, encoding=encoding)
        f_out.write(json_str)#python自带的write
        f_out.close()
        
"""
函数说明:保存数据为JSON
    .json

Parameters:
    table_dict - 字典类型 key-DatFrame(表)
    keyword  -  最终输出的json的文件名
Returns:
Author:
    heda3
Blog:
    https://blog.csdn.net/heda3
Modify:
    2019-10-12
"""
def gen_json(table_dict, keyword):
    list_dic = []
    for i in list(table_dict.keys()):
        list_dic.append((i, table_dict[i]))
    dic = OrderedDict(list_dic)#字典key-DataFrame
    list_json = WriterJson().odict_to_json(dic)#list内嵌套了dict和list多层
    WriterJson().write_json(json_list=list_json, file_name=keyword+'.json')
#保存为Json格式的数据 该文件为str
keyword='数据名测试2'
table_dict1=tuple_dicts[0]
gen_json(table_dict1,keyword)

pandas 的 数据表转换为jsonstr:. to_json()函数的用法

其中的‘table’模式:

from collections import OrderedDict 库参考文档:

https://docs.python.org/zh-cn/3.7/library/collections.html#collections.OrderedDict

codecs编码

转换过程:原有编码--python内部编码(unicode)--目标编码

https://blog.csdn.net/suofiya2008/article/details/5579413

参考文档

1、loadtxt 函数使用https://www.numpy.org/devdocs/reference/generated/numpy.loadtxt.html?highlight=loadtxt#numpy.loadtxt

2、https://blog.csdn.net/ACID_lv_ing/article/details/87092714

3、numpy.loadtxt https://numpy.org/devdocs/reference/generated/numpy.loadtxt.html?highlight=loadtxt#numpy.loadtxt

4、过滤缺失数据  dropna -pandas 参考文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html

5、Json 文档 https://www.runoob.com/json/json-syntax.html

6、Json包 https://docs.python.org/zh-cn/3.7/library/json.html

7、https://www.cnblogs.com/tjuyuan/p/6795860.html

8、天眼查项目 https://github.com/qzcool/Tianyancha 

9.pandas 数据表转换为json https://blog.csdn.net/huanbia/article/details/72674832

pandas.DataFrame.to_json https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_json.html

10、JSON 编码和解码器官方文档 https://docs.python.org/zh-cn/3.7/library/json.html

发布了136 篇原创文章 · 获赞 112 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/heda3/article/details/99710410
今日推荐