python数据的加载和存储(针对*.json,*.csv,*.xls,*.xlsx,*.text等格式的文件的读取和修改操作,还有python实现与数据库的交互)

一对json,csv,xlst,txet等文件的python操作

使用python中的pandas模块,pandas提供的读取方法将表格型数据读取为DataFrame对象的函数

import pandas as pd

1.针对json格式的操作:

读取方法:pd.read_json(filepath,sep=".",dtype="",encoding="",index_col="",header="")

filepath表示的是json格式文件的路径;sep接收string,dtype接收dict,代表写入的数据类型;

encoding用于unicode的文本编码格式,列如:“utf-8”等;index_col接受int,sequence或False,表示索引列的位置,取值为sequence则代表多重索引,默认为Nonde;header接收int和sequence,将某行数据作为列名,默认为infer,表示自动识别。

写入方法:使用to_json()方法将数据写入文件

df.to_json(path_or_buf,sep,na_rep,columns,header,.index,index_labels,mode,encoding)

path_or_buf表示文件的路径;sep表示分隔符,默认为“,”;na_rep接受string,表示缺失值。默认“”;columns接受list,代表写出的列名,默认为None;header接受boolean,代表是否将列名写出,默认为True;index接受boolean,代表是否将行名写出,默认为True;index_labels接收sequence,默认None;mode接受特定的string,代表写入数据模式,默认为w;encoding代表编码格式。

其他的操作:json.loads()函数将JSON字符串转化为python形式

例:

s = '{"name": "wade", "age": 54, "gender": "man"}'
# json.loads读取字符串并转为Python对象
print("json.loads将字符串转为Python对象: type(json.loads(s)) = {}".format(type(json.loads(s))))
print("json.loads将字符串转为Python对象: json.loads(s) = {}".format(json.loads(s)))

# json.load读取文件并将文件内容转为Python对象
# 数据文件要s.json的内容 --> {"name": "wade", "age": 54, "gender": "man"}
with open('../file/6.json', 'r') as f:
    s1 = json.load(f)
print("json.load将文件内容转为Python对象: type(json.load(f)) = {}".format(type(s1)))
print("json.load将文件内容转为Python对象: json.load(f) = {}".format(s1))

注:所有read_()方法的参数的大都相同下面不详细介绍,如果读取含有缺失值的文件,pandas会默认使用

NaN进行替代。

注:所有to_ ()读入文件数据的方法,读入的数据必须是DataFrame格式的数据

2.针对csv,text,xls等格式文件的操作

text读取方法:pd.read_table(),pd.read_csv()

csv读取方法:pd.read_csv()

xls,xlsx读取方法:pd.read_excel()

xls,csv,text等写入文件的方法:to_csv(),to_xls(),to_text()

3.实现与数据库的交互

python实现与数据库连接:

create_engine('mysql+pymysql://root:root@localhost:3306/mysqlone')

参数:固定为'mysql+pymysql://root:root@localhost:3306/数据库的名字'

from sqlalchemy import create_engine
import numpy as np
import pandas as pd

# # 建立一个mysql的连接器,用户名root,没有密码
# # 地址为localhost,数据库名为mydb,连接本机的数据库
conn=create_engine('mysql+pymysql://root:root@localhost:3306/mysqlone')
# 使用read_sql_table()读取订单表的数据,只能读取表
info=pd.read_sql_table('activity',con=conn);
# 使用read_sql_query()执行sql语句
result=pd.read_sql_query("select * from activity",con=conn)
# print("订单表中记录数为",len(result))
# 使用read_sql()读取表,或者执行sql语句
result= pd.read_sql("activity",con=conn)
result=pd.read_sql("select id,user_name,leader_phone from activity ",con=conn)

# 数据库的储存使用to_sql()语句实现
# 将字典的数据存入表
dict_info={"name":[0,1,2],"age":["wangchonh","liyang","nihao"],"weight":[150,120,110],"gender":["man","woman","man"]}
df=pd.DataFrame(dict_info)
# 如果user_info该表存在,就删除重新创建,不存在就创建
df.to_sql("user_info",con=conn,index=False,if_exists="replace")
result=pd.read_sql("select * from user_info",con=conn)
print(result)

to_sql()方法

使用DataFrame.to_sql(name,con,if_exists=””,index=True,index_label=None,dtype=None)

猜你喜欢

转载自blog.csdn.net/qq_51269815/article/details/121492269