人人都会AI编程

12.4 常用文件格式处理:CSV、JSON、XML、INI 配置文件

更新时间:2026-07-12

在实际开发中,文件绝不仅限于纯文本。配置、数据交换、日志记录经常以 CSV、JSON、XML、INI 等结构化格式存在。Python 标准库已为这些常见格式提供了开箱即用的支持,掌握它们能让文件处理事半功倍。

CSV(逗号分隔值)

CSV 是表格数据交换的“通用语”,Excel、数据库、数据分析工具都能直接读写。

  • 读取:用 csv.reader 迭代每一行,或 csv.DictReader 将每行转成字典,方便按列名访问。
  • 写入:用 csv.writer 写入列表,或 csv.DictWriter 写入字典。
import csv

# 读取为字典列表
with open('users.csv', 'r', newline='', encoding='utf-8') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['name'], row['email'])

# 写入
with open('output.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'email'])
    writer.writeheader()
    writer.writerow({'name': '张三', 'email': 'zhangsan@example.com'})
  • 注意点:务必指定 newline='' 防止在 Windows 下多出空行;处理包含逗号或换行的字段时,csv 模块会自动用引号包裹。

JSON(JavaScript 对象表示法)

JSON 是 Web API 和配置文件的主流格式,轻量、易读、语言无关。

  • 核心方法json.load() 从文件对象直接读取解析;json.dump() 将 Python 对象序列化写入文件;json.loads()json.dumps() 则处理字符串。
  • 复杂对象处理:普通 dict/list 可直接序列化,遇到 datetime 等非标准类型需要自定义 default 或编码逻辑。
import json

# 读取 JSON 文件
with open('config.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    print(data['server']['port'])

# 写入 JSON 文件
config = {'server': {'host': 'localhost', 'port': 8080}}
with open('config.json', 'w', encoding='utf-8') as f:
    json.dump(config, f, indent=2, ensure_ascii=False)
  • 注意点ensure_ascii=False 保证中文直接显示而不是转成 \u 编码;indent 让输出更可读。

XML(可扩展标记语言)

XML 用于一些遗留系统、配置文件(如 Maven 的 pom.xml)和某些 API。标准库 xml.etree.ElementTree 提供了轻量级解析。

  • 解析ET.parse() 读取文件得到 ElementTree 对象,getroot() 获取根元素,再通过 findfindalliter 定位节点,.text 获取内容。
  • 构建与写入:创建 Element 对象组装树,用 ET.ElementTree 写入文件。
import xml.etree.ElementTree as ET

# 解析 XML
tree = ET.parse('data.xml')
root = tree.getroot()
for item in root.findall('item'):
    name = item.find('name').text
    print(name)

# 生成 XML
root = ET.Element('catalog')
book = ET.SubElement(root, 'book', id='1')
title = ET.SubElement(book, 'title')
title.text = 'Python入门'
tree = ET.ElementTree(root)
tree.write('output.xml', encoding='utf-8', xml_declaration=True)
  • 适用场景:当第三方系统要求 XML 格式时,标准库的 ElementTree 足够简单应对。对于超大型 XML 文件,可用 iterparse 增量处理节省内存。

INI 配置文件

INI 格式常见于传统 Windows 应用和一些简单程序配置,结构为 [section] 下的键值对。Python 的 configparser 模块专门处理此类文件。

  • 读取config.read() 加载文件,然后像访问字典一样用 config['section']['key'] 获取值。
  • 写入:先构建 ConfigParser 对象,添加节和键值,最后写入文件。
import configparser

# 读取 INI
config = configparser.ConfigParser()
config.read('settings.ini')
host = config['database']['host']
port = config.getint('database', 'port')

# 写入 INI
config = configparser.ConfigParser()
config['server'] = {'host': '0.0.0.0', 'port': '8080'}
config['database'] = {'user': 'root', 'password': 'secret'}
with open('app.ini', 'w') as f:
    config.write(f)
  • 注意点configparser 会自动将键名转为小写,且值都是字符串,需要 getint() / getboolean() 等方法来转换类型。

选择建议

  • CSV:表格数据、数据交换、对接 Excel/数据库。
  • JSON:Web API、跨语言数据结构、现代配置文件。
  • XML:遗留系统对接、需要命名空间或复杂结构时。
  • INI:简单的应用程序配置,追求 [section] 的可读性。

真实项目中,JSON 和 CSV 使用频率最高。无论哪种格式,都用 with 语句管理文件,处理好编码(统一 UTF-8),这些标准模块就能稳定工作。