Python操作XML与CONFIG文件:从读取到修改与删除的详细指南
在日常开发中,配置文件(如 .xml
和 .config
文件)是存储应用程序设置和数据的重要方式。Python 提供了多种工具来操作这些文件。本文将详细介绍如何使用 Python 读取、写入、修改和删除 .xml
和 .config
文件中的内容。
1. 操作 XML 文件
XML(可扩展标记语言)是一种常用的数据存储和传输格式。Python 提供了多种库来操作 XML 文件,以下是详细的操作方法。
1.1 读取 XML 文件
使用 xml.etree.ElementTree
(标准库)
import xml.etree.ElementTree as ET # 打开并解析 XML 文件 tree = ET.parse('xml.xml') # 替换为你的 XML 文件路径 root = tree.getroot() # 获取根元素 # 遍历 XML 文件 for child in root: print(f"Tag: {child.tag}, Attributes: {child.attrib}") for subchild in child: print(f" Subtag: {subchild.tag}, Text: {subchild.text}")![]()
![]()
1.2 写入 XML 文件
添加新元素
import xml.etree.ElementTree as ET
# 打开并解析 XML 文件
tree = ET.parse('example.xml')
root = tree.getroot()# 创建新元素
new_item = ET.Element('item', {'id': '3'})
name = ET.SubElement(new_item, 'name')
name.text = 'Orange'
price = ET.SubElement(new_item, 'price')
price.text = '0.75'# 将新元素添加到根元素
root.append(new_item)# 保存修改后的 XML 文件
tree.write('example.xml')import xml.etree.ElementTree as ET
# 打开并解析 XML 文件
tree = ET.parse('example.xml')
root = tree.getroot()# 创建新元素
new_item = ET.Element('item', {'id': '3'})
name = ET.SubElement(new_item, 'name')
name.text = 'Orange'
price = ET.SubElement(new_item, 'price')
price.text = '0.75'# 将新元素添加到根元素
root.append(new_item)# 保存修改后的 XML 文件
tree.write('example.xml')
1.3 修改 XML 文件
修改元素内容
import xml.etree.ElementTree as ET
# 打开并解析 XML 文件
tree = ET.parse('example.xml')
root = tree.getroot()# 查找需要修改的元素
for item in root.findall('item'):
if item.get('id') == '1':
item.find('price').text = '1.50' # 修改价格# 保存修改后的 XML 文件
tree.write('example.xml')
1.4 删除 XML 文件中的元素
删除指定元素
import xml.etree.ElementTree as ET
# 打开并解析 XML 文件
tree = ET.parse('example.xml')
root = tree.getroot()# 查找并删除指定元素
for item in root.findall('item'):
if item.get('id') == '2':
root.remove(item) # 删除元素# 保存修改后的 XML 文件
tree.write('example.xml')
2. 操作 CONFIG 文件
CONFIG 文件通常用于存储应用程序的配置信息。Python 提供了多种方法来操作 CONFIG 文件,以下是详细的操作方法。
2.1 读取 CONFIG 文件
使用 configparser
(标准库)
import configparser
# 创建 ConfigParser 对象
config = configparser.ConfigParser()# 打开并解析 CONFIG 文件
config.read('example.config') # 替换为你的 CONFIG 文件路径# 读取配置项
for section in config.sections():
print(f"[{section}]")
for key in config[section]:
print(f"{key} = {config[section][key]}")
2.2 写入 CONFIG 文件
添加新配置项
import configparser
# 创建 ConfigParser 对象
config = configparser.ConfigParser()# 打开并解析 CONFIG 文件
config.read('example.config')# 添加新 SECTION 和配置项
config['database'] = {
'host': 'localhost',
'port': '3306',
'username': 'admin',
'password': 'secret'
}# 保存修改后的 CONFIG 文件
with open('example.config', 'w') as configfile:
config.write(configfile)
2.3 修改配置项
修改现有配置项
import configparser # 创建 ConfigParser 对象 config = configparser.ConfigParser() # 打开并解析 CONFIG 文件 config.read('example.config') # 修改配置项 config['user']['Name'] = 'xiao' config['database']['port'] = '5432' # 保存修改后的 CONFIG 文件 with open('example.config', 'w') as configfile: config.write(configfile)
2.4 删除配置项
删除指定配置项
import configparser # 创建 ConfigParser 对象 config = configparser.ConfigParser() # 打开并解析 CONFIG 文件 config.read('example.config') # 删除指定配置项 config.remove_option('user', 'Email') # 保存修改后的 CONFIG 文件 with open('example.config', 'w') as configfile: config.write(configfile)
2.5 删除整个 SECTION
删除指定 SECTION
import configparser # 创建 ConfigParser 对象 config = configparser.ConfigParser() # 打开并解析 CONFIG 文件 config.read('example.config') # 删除指定 SECTION config.remove_section('database') # 保存修改后的 CONFIG 文件 with open('example.config', 'w') as configfile: config.write(configfile)
作者:帆.