一、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_str=json.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_obj=json.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_str=json.dumps(dict1) print(j_str,type(j_str)) # 2.将json字符串转化为字典 data=json.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_data=json.load(file) print(load_data)学习资料连接:
python基础库之json库_哔哩哔哩_bilibili
二、csv
1.读取csv文件
一般写法
import csv # 1.读取csv文件 path=r"E:\360MoveData\Users\asus\Desktop\海算卫士封装测试\测试数据\test_write_csv.csv" f=open(path,encoding='UTF8') csv_reader=csv.reader(f) print(csv_reader) for line in csv_reader: print(line,type(line)) f.close()with写法
import csv path=r"E:\360MoveData\Users\asus\Desktop\海算卫士封装测试\测试数据\test_write_csv.csv" with open(path,encoding="utf-8") as f: csv_reader=csv.reader(f) print(csv_reader) for line in csv_reader: print(line,type(line))2.写csv
一般写法
import csv path=r"E:\360MoveData\Users\asus\Desktop\海算卫士封装测试\测试数据\test_write_csv.csv" f=open(path,newline="") # 记得一定要加newline=""否则生成的csv文件行与行之间存在空行 write_csv=csv.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 path=r"E:\360MoveData\Users\asus\Desktop\海算卫士封装测试\测试数据\test_write_csv.csv" with open(path,mode="w",newline="") as f: # # 记得一定要加newline=""否则生成的csv文件行与行之间存在空行 write_csv=csv.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文件_哔哩哔哩_bilibili
3.写入字典
import csv # 表头(字段名) headers = ["id", "name", "amount"] # 数据:字典列表 data = [ {"id": 1, "name": "张三", "amount": 99.9}, {"id": 2, "name": "李四", "amount": 120.56} ] # 写入文件 with open("test.csv", "w", encoding="utf-8", newline="") as f: # 创建DictWriter对象 writer = csv.DictWriter(f, fieldnames=headers) # 写入表头行 writer.writeheader() # 写入单行字典 writer.writerow({"id": 3, "name": "王五", "amount": 50.0}) # 批量写入多行 writer.writerows(data)三、logging
1.基本用法
import logging # 设置logging等级,低于该等级消息不会出现,默认等级level=logging.WARNING # 等级顺序从低至高依次为debug,info,warning,error,critical logging.basicConfig(level=logging.WARNING, format="%(asctime)s-%(name)s-%(levelno)s", filename='log.txt', filemode='w') # 用在下面语句之前 logging.debug("deg msg") logging.info("info msg") logging.warning("warning msg") logging.error("error msg") logging.critical("critical msg")2.自定义logging
import logging # 设置logging等级,低于该等级消息不会出现,默认等级level=logging.WARNING # 等级顺序从低至高依次为debug,info,warning,error,critical test_logger=logging.getLogger("test_logger") file_handler=logging.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等级,低于该等级消息不会出现,默认等级level=logging.WARNING # 等级顺序从低至高依次为debug,info,warning,error,critical test_logger=logging.getLogger("test_logger") file_handler=logging.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模块怎么用_哔哩哔哩_bilibili
4.python logging.basicConfig参数
logging.basicConfig是 Pythonlogging模块中用于配置日志记录的一个方便函数。以下是对其主要参数的详细解释:
参数说明
filename:- 类型:
str - 作用:指定日志输出的文件名。如果提供了此参数,日志信息将被写入文件而不是控制台。
- 示例:
收起
python
import logging logging.basicConfig(filename='example.log')- 类型:
filemode:- 类型:
str - 作用:指定文件的打开模式,默认为
'a'(追加模式),可以使用'w'(写入模式)。 - 示例:
收起
python
import logging logging.basicConfig(filename='example.log', filemode='w')- 类型:
format:- 类型:
str - 作用:指定日志消息的格式。使用特定的格式字符串来定义日志消息的外观。
- 常见格式占位符:
%(asctime)s:日志的时间,默认为'2003-07-08 16:49:45,896'这种形式。%(levelname)s:日志级别,如DEBUG,INFO,WARNING,ERROR,CRITICAL。%(name)s:日志记录器的名称。%(message)s:日志消息。%(levelno)s:日志级别的数字表示。
- 示例:
收起
python
import logging logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')- 类型:
datefmt:- 类型:
str - 作用:指定日期 / 时间的格式,与
%(asctime)s一起使用。 - 示例:
收起
python
import 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)。 - 示例:
收起
python
import logging logging.basicConfig(level=logging.INFO)- 类型:
handlers:- 类型:
list - 作用:指定日志处理器列表。可以将日志信息发送到多个目标,如文件、控制台、邮件等。
- 示例:
收起
python
import logging from logging.handlers import RotatingFileHandler handler = RotatingFileHandler('example.log', maxBytes=2000, backupCount=5) logging.basicConfig(handlers=[handler])- 类型:
示例
以下是一个综合使用logging.basicConfig的示例:
收起
python
import logging logging.basicConfig( filename='example.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.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')解释:
filename='example.log'和filemode='w'表示将日志信息以写入模式保存到example.log文件中。format='%(asctime)s - %(levelname)s - %(message)s'和datefmt='%Y-%m-%d %H:%M:%S'定义了日志消息的格式和日期格式。level=logging.INFO表示只输出INFO及以上级别的日志信息。
注意事项
- 一旦调用
logging.basicConfig并设置了配置,后续调用不会重新配置日志系统,除非使用force=True参数。 - 对于更复杂的日志需求,可能需要使用
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.设置邮件服务器 sever=smtplib.SMTP("smtp.126.com",25) sever.starttls() # 3.登录邮箱 sever.login("haisuan0898@126.com","HWtg7SQL6rDqFBuR") # todo 切记此处不可以使用邮箱密码,而应使用网易授权密码,此密码在网易邮箱设置pop3位置获取 # 4.创建邮箱内容 msg=MIMEText("Hello,Python to email~~") msg["Subject"]="Test Python email" msg["from"]="haisuan0898@126.com" msg["to"]="835670272@qq.com" # 5.发送邮件 sever.sendmail("haisuan0898@126.com","835670272@qq.com",msg.as_string()) # 6.关闭连接 sever.close()