1. 什么是异常,如何捕获处理异常,比如捕获“1除以0”的异常
在 Python 中,异常(Exception) 是指程序运行过程中发生的错误。这些错误会中断程序的正常执行流程。
try:
result = 1 / 0
except Exception as e:
print("发生异常:", e)
2. 如何自定义异常,自己主动抛出异常并捕获,比如定义一个列表,随机添加几个数字元素,当元素的总值高于某个值时,抛出异常。
你可以通过继承 Exception 类来自定义异常类型。结合条件判断,你可以在满足特定条件时主动抛出异常,并使用 try...except 捕获和处理它。
import random
# 自定义异常类
class TotalTooLargeError(Exception):
def __init__(self, message="列表元素总值超过限制"):
self.message = message
super().__init__(self.message)
# 主程序逻辑
try:
# 初始化空列表
numbers = []
# 随机添加几个整数(比如5个)
for _ in range(5):
numbers.append(random.randint(1, 20))
print(f"当前列表: {numbers}, 当前总值: {sum(numbers)}")
# 判断是否超出限制
if sum(numbers) > 100:
raise TotalTooLargeError(f"当前总值 {sum(numbers)} 超过限制 100")
except TotalTooLargeError as e:
print("捕获到自定义异常:", e)
3. 将一个字典保存为json文件
import json
# 定义一个字典
data = {
"name": "Alice",
"age": 30,
"city": "Shanghai",
"is_student": False,
"hobbies": ["reading", "coding", "traveling"]
}
4. 读取一个json文件为字典格式
import json
# JSON 文件路径
file_path = "data.json"
# 读取 JSON 文件并转换为字典
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
print("读取成功,内容如下:")
print(data)
5. 如何创建一个csv文件
import csv
# 定义要写入的数据(第一行为表头)
data = [
["姓名", "年龄", "城市"],
["Alice", 30, "上海"],
["Bob", 25, "北京"],
["Charlie", 28, "广州"]
]
# 创建并写入 CSV 文件
file_path = "people.csv"
with open(file_path, mode='w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data)
print(f"CSV 文件已成功创建:{file_path}")
6. 什么是序列化和反序列化
1. 序列化(Serialization)
含义:将内存中复杂的数据结构(如字典、列表等对象),转换为可存储或传输的格式(如 JSON 字符串、二进制数据等)。
用途:
将数据保存到文件(例如写入 JSON 文件)
在网络上传输数据(如 REST API 请求/响应)
2. 反序列化(Deserialization)
含义:将序列化后的数据(如 JSON 字符串、二进制数据等)还原为内存中的数据结构(如字典、列表等)。
用途:
从文件读取数据
接收并解析来自网络的数据
7. Python如何将一个对象序列化为一个文件。如何读取此文件并反序列化为对象。
1.使用json模块:
序列化:
import json
# 示例对象(字典)
data = {
"name": "Alice",
"age": 30,
"city": "上海"
}
# 写入 JSON 文件
file_path = "data.json"
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
print(f"数据已序列化到 {file_path}")反序列化:
with open(file_path, 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print("反序列化结果:", loaded_data)2.使用 pickle 模块
序列化:
import pickle
# 示例对象(可以是任意复杂结构)
class Person:
def __init__(self, name, age, city):
self.name = name
self.age = age
self.city = city
person_obj = Person("Bob", 25, "北京")
# 写入 Pickle 文件
file_path = "person.pkl"
with open(file_path, 'wb') as f:
pickle.dump(person_obj, f)
print(f"对象已序列化到 {file_path}")反序列化:
# 从 Pickle 文件读取并还原为对象
with open(file_path, 'rb') as f:
loaded_obj = pickle.load(f)
print("反序列化对象:")
print("Name:", loaded_obj.name)
print("Age:", loaded_obj.age)
print("City:", loaded_obj.city)
8. xml格式是什么,python如何读取解析xml文件
以下为示例:
<?xml version='1.0' encoding='utf-8'?>
<library>
<book>
<title>Python编程入门</title>
<author>张三</author>
<year>2020</year>
</book>
<book>
<title>深入学习Python</title>
<author>李四</author>
<author>王五</author>
<year>2021</year>
</book>
</library>创建xml
import xml.etree.ElementTree as ET
# 创建根元素 <library>
library = ET.Element("library")
# 创建第一个 <book> 及其子元素
book1 = ET.SubElement(library, "book")
ET.SubElement(book1, "title").text = "Python编程入门"
ET.SubElement(book1, "author").text = "张三"
ET.SubElement(book1, "year").text = "2020"
# 创建第二个 <book> 及其子元素
book2 = ET.SubElement(library, "book")
ET.SubElement(book2, "title").text = "深入学习Python"
ET.SubElement(book2, "author").text = "李四"
ET.SubElement(book2, "author").text = "王五"
ET.SubElement(book2, "year").text = "2021"
# 构建整个 XML 树
tree = ET.ElementTree(library)
# 保存为文件,并指定编码为 utf-8 和 XML 声明
tree.write("library.xml", encoding="utf-8", xml_declaration=True)
print("XML 文件已成功创建:library.xml")解析并打印
import xml.etree.ElementTree as ET
# 加载并解析 XML 文件
file_path = "library.xml"
tree = ET.parse(file_path)
root = tree.getroot()
# 遍历所有 <book> 节点
for book in root.findall('book'):
title = book.find('title').text
authors = [author.text for author in book.findall('author')]
year = book.find('year').text
print(f"书名: {title}")
print(f"作者: {', '.join(authors)}")
print(f"出版年份: {year}")
print("-" * 30)
9. 读取上面的xml,转换为json格式,并保存为文件book.json
转换成这样:
{
"library": {
"book": [
{
"title": "Python编程入门",
"author": "张三",
"year": 2020
},
{
"title": "深入学习Python",
"author": [
"李四",
"王五"
],
"year": 2021
}
]
}
}读取并转换成Json
import xml.etree.ElementTree as ET
import json
# 解析 XML 文件
tree = ET.parse("library.xml")
root = tree.getroot()
# 初始化最终的 JSON 数据结构
library_data = {
"library": {
"book": []
}
}
# 遍历每个 <book> 节点
for book in root.findall("book"):
title = book.find("title").text
authors = [author.text for author in book.findall("author")]
year = int(book.find("year").text)
# 处理作者字段(单个或多个)
if len(authors) == 1:
authors = authors[0] # 单作者转为字符串
library_data["library"]["book"].append({
"title": title,
"author": authors,
"year": year
})
# 将数据写入 JSON 文件
file_path = "book.json"
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(library_data, f, ensure_ascii=False, indent=4)
print(f"JSON 文件已成功保存到 {file_path}")
10. 读取book.json文件,转为xml格式,并保存为文件book.xml
import json
import xml.etree.ElementTree as ET
# 读取 JSON 文件
with open("book.json", "r", encoding="utf-8") as f:
data = json.load(f)
# 创建根节点 <library>
library = ET.Element("library")
# 遍历所有书籍条目
for book_data in data["library"]["book"]:
book = ET.SubElement(library, "book")
# 添加 title 字段
title = ET.SubElement(book, "title")
title.text = book_data["title"]
# 处理 author 字段(可能是字符串或列表)
authors = book_data["author"]
if isinstance(authors, str):
author = ET.SubElement(book, "author")
author.text = authors
else:
for author_name in authors:
author = ET.SubElement(book, "author")
author.text = author_name
# 添加 year 字段
year = ET.SubElement(book, "year")
year.text = str(book_data["year"])
# 构建 XML 树并写入文件
tree = ET.ElementTree(library)
tree.write("book.xml", encoding="utf-8", xml_declaration=True)
print("XML 文件已成功保存为:book.xml")