python 基础类json和csv

python 基础类json和csv 一、json两个重要的方法json.dumps()Python 对象 →转成 JSON 字符串序列化json.loads()JSON 字符串 →转回 Python 对象反序列化通过下面的测试代码可以发现上面两种方法支持dict、list、int、float、bool、None 、 str共7种数据类型的互相转换完全不支持set类型。json.dumps可以转换tuple类型但是使用json.loads再转换回来则成了list数据类型。import json list1[张三,1,1.6,True,None,[a,b,c],(a,b,c),{a,b,c},{a:1,b:2,c:3}] # 支持转为json字符串的数据类型 json_dict{} json_strs[] # 不支持转json字符串的数据类型 json_list2[] for i in list1: try: json_strjson.dumps(i) # json_list1.append(type(i)) json_strs.append(json_str) json_dict[type(i)]json_str except: json_list2.append(type(i)) print(json_dict) print(json_list2) print(json_strs) py_dict{} for i in json_strs: py_objjson.loads(i) py_dict[type(py_obj)]py_obj print(py_dict)1.将字典转换为json字符串2.将json字符串转化为字典3.将字典保存为json文件4.将json文件读取出字典格式的数据import json # 1.将字典转化成json字符串 dict1{张三:zhangsan,B:b,C:c} j_strjson.dumps(dict1) print(j_str,type(j_str)) # 2.将json字符串转化为字典 datajson.loads(j_str) print(data) # 3.将字典数据写入json文件 with open(data.json,w) as file: json.dump(data,file) # 4.将json文件中的数据读取出来 with open(data.json,r) as file: load_datajson.load(file) print(load_data)学习资料连接python基础库之json库_哔哩哔哩_bilibili二、csv1.读取csv文件一般写法import csv # 1.读取csv文件 pathrE:\360MoveData\Users\asus\Desktop\海算卫士封装测试\测试数据\test_write_csv.csv fopen(path,encodingUTF8) csv_readercsv.reader(f) print(csv_reader) for line in csv_reader: print(line,type(line)) f.close()with写法import csv pathrE:\360MoveData\Users\asus\Desktop\海算卫士封装测试\测试数据\test_write_csv.csv with open(path,encodingutf-8) as f: csv_readercsv.reader(f) print(csv_reader) for line in csv_reader: print(line,type(line))2.写csv一般写法import csv pathrE:\360MoveData\Users\asus\Desktop\海算卫士封装测试\测试数据\test_write_csv.csv fopen(path,newline) # 记得一定要加newline否则生成的csv文件行与行之间存在空行 write_csvcsv.writer(f) # 写入单行 headLabel[name, age, score] write_csv.writerow(headLabel) # 写入多行 content[[zhangsan, 18, 81],[lisi, 19, 78],[wangwu, 17, 92]] write_csv.writerows(content) f.close()with写法import csv pathrE:\360MoveData\Users\asus\Desktop\海算卫士封装测试\测试数据\test_write_csv.csv with open(path,modew,newline) as f: # # 记得一定要加newline否则生成的csv文件行与行之间存在空行 write_csvcsv.writer(f) # 写入单行 headLabel [name, age, score] write_csv.writerow(headLabel) # 写入多行 content [[zhangsan, 18, 81], [lisi, 19, 78], [wangwu, 17, 92]] write_csv.writerows(content)学习资料链接跟峰哥学编程-Python入门-40.读写CSV文件_哔哩哔哩_bilibili3.写入字典import csv # 表头字段名 headers [id, name, amount] # 数据字典列表 data [ {id: 1, name: 张三, amount: 99.9}, {id: 2, name: 李四, amount: 120.56} ] # 写入文件 with open(test.csv, w, encodingutf-8, newline) as f: # 创建DictWriter对象 writer csv.DictWriter(f, fieldnamesheaders) # 写入表头行 writer.writeheader() # 写入单行字典 writer.writerow({id: 3, name: 王五, amount: 50.0}) # 批量写入多行 writer.writerows(data)三、logging1.基本用法import logging # 设置logging等级低于该等级消息不会出现默认等级levellogging.WARNING # 等级顺序从低至高依次为debuginfowarningerrorcritical logging.basicConfig(levellogging.WARNING, format%(asctime)s-%(name)s-%(levelno)s, filenamelog.txt, filemodew) # 用在下面语句之前 logging.debug(deg msg) logging.info(info msg) logging.warning(warning msg) logging.error(error msg) logging.critical(critical msg)2.自定义loggingimport logging # 设置logging等级低于该等级消息不会出现默认等级levellogging.WARNING # 等级顺序从低至高依次为debuginfowarningerrorcritical test_loggerlogging.getLogger(test_logger) file_handlerlogging.FileHandler(test_logger.txt,w) file_handler.setFormatter(logging.Formatter(%(asctime)s-%(name)s-%(levelno)s)) test_logger.addHandler(file_handler) test_logger.error(error mgs)3.用logging记录异常import logging # 设置logging等级低于该等级消息不会出现默认等级levellogging.WARNING # 等级顺序从低至高依次为debuginfowarningerrorcritical test_loggerlogging.getLogger(test_logger) file_handlerlogging.FileHandler(test_logger_get_exception.txt,w) file_handler.setFormatter(logging.Formatter(%(asctime)s-%(name)s-%(levelno)s)) test_logger.addHandler(file_handler) try: 1/0 except: test_logger.exception(Get exception)学习资料连接[Python] logging模块怎么用_哔哩哔哩_bilibili4.python logging.basicConfig参数logging.basicConfig是 Pythonlogging模块中用于配置日志记录的一个方便函数。以下是对其主要参数的详细解释参数说明filename类型str作用指定日志输出的文件名。如果提供了此参数日志信息将被写入文件而不是控制台。示例收起pythonimport logging logging.basicConfig(filenameexample.log)filemode类型str作用指定文件的打开模式默认为a追加模式可以使用w写入模式。示例收起pythonimport logging logging.basicConfig(filenameexample.log, filemodew)format类型str作用指定日志消息的格式。使用特定的格式字符串来定义日志消息的外观。常见格式占位符%(asctime)s日志的时间默认为2003-07-08 16:49:45,896这种形式。%(levelname)s日志级别如DEBUG,INFO,WARNING,ERROR,CRITICAL。%(name)s日志记录器的名称。%(message)s日志消息。%(levelno)s日志级别的数字表示。示例收起pythonimport logging logging.basicConfig(format%(asctime)s - %(levelname)s - %(message)s)datefmt类型str作用指定日期 / 时间的格式与%(asctime)s一起使用。示例收起pythonimport logging logging.basicConfig(format%(asctime)s - %(levelname)s - %(message)s, datefmt%Y-%m-%d %H:%M:%S)level类型int或str作用设置日志的最低输出级别。低于此级别的日志消息将被忽略。可以使用logging.DEBUG,logging.INFO,logging.WARNING,logging.ERROR,logging.CRITICAL或相应的整数10, 20, 30, 40, 50。示例收起pythonimport logging logging.basicConfig(levellogging.INFO)handlers类型list作用指定日志处理器列表。可以将日志信息发送到多个目标如文件、控制台、邮件等。示例收起pythonimport logging from logging.handlers import RotatingFileHandler handler RotatingFileHandler(example.log, maxBytes2000, backupCount5) logging.basicConfig(handlers[handler])示例以下是一个综合使用logging.basicConfig的示例收起pythonimport logging logging.basicConfig( filenameexample.log, filemodew, format%(asctime)s - %(levelname)s - %(message)s, datefmt%Y-%m-%d %H:%M:%S, levellogging.INFO ) # 输出不同级别的日志 logging.debug(This is a debug message) logging.info(This is an info message) logging.warning(This is a warning message) logging.error(This is an error message) logging.critical(This is a critical message)解释filenameexample.log和filemodew表示将日志信息以写入模式保存到example.log文件中。format%(asctime)s - %(levelname)s - %(message)s和datefmt%Y-%m-%d %H:%M:%S定义了日志消息的格式和日期格式。levellogging.INFO表示只输出INFO及以上级别的日志信息。注意事项一旦调用logging.basicConfig并设置了配置后续调用不会重新配置日志系统除非使用forceTrue参数。对于更复杂的日志需求可能需要使用Logger,Handler,Formatter等类进行更详细的日志系统配置。通过使用logging.basicConfig的这些参数可以方便地设置基本的日志记录功能满足大多数简单的日志需求。对于更复杂的日志系统可以深入研究logging模块的其他部分如FileHandler,StreamHandler,Formatter等。除了logging.basicConfig还有哪些方法可以配置Python的日志记录如何在日志消息中包含更多的上下文信息如何在生产环境中配置日志记录四、电子邮件1.学习资料来源本内容绑定视频资源讲述python发送邮件的基本步骤示例代码即在此基础上改写而来。2.关于授权密码的设置3.示例代码# 1.导包 import smtplib from email.mime.text import MIMEText # 2.设置邮件服务器 seversmtplib.SMTP(smtp.126.com,25) sever.starttls() # 3.登录邮箱 sever.login(haisuan0898126.com,HWtg7SQL6rDqFBuR) # todo 切记此处不可以使用邮箱密码而应使用网易授权密码此密码在网易邮箱设置pop3位置获取 # 4.创建邮箱内容 msgMIMEText(Hello,Python to email~~) msg[Subject]Test Python email msg[from]haisuan0898126.com msg[to]835670272qq.com # 5.发送邮件 sever.sendmail(haisuan0898126.com,835670272qq.com,msg.as_string()) # 6.关闭连接 sever.close()