在Python中,文件读写是一个基础且重要的功能,它允许我们与存储在磁盘上的数据进行交互。下面,我将分别展示如何使用Python来读写txt、json、xml和ini格式的文件,并附上详细的代码讲解。
1. 读写TXT文件
写入TXT文件
# 打开(或创建)一个txt文件用于写入,如果文件已存在则会被覆盖
with open('example.txt', 'w', encoding='utf-8') as file:
file.write('Hello, World!\n') # 写入一行文本
file.write('这是第二行文本。\n') # 写入另一行文本
# 使用with语句可以确保文件正确关闭
读取TXT文件
# 打开txt文件用于读取
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read() # 读取整个文件内容
print(content)
# 或者逐行读取
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line, end='') # end='' 防止打印额外的换行符
2. 读写JSON文件
写入JSON文件
import json
data = {
'name': 'John Doe',
'age': 30,
'is_student': False
}
# 将字典写入JSON文件
with open('data.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4) # ensure_ascii=False允许写入非ASCII字符,indent用于美化输出
读取JSON文件
# 读取JSON文件
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
print(data)
print(data['name']) # 访问字典中的值
3. 读写XML文件
Python标准库中没有直接处理XML的模块,但xml.etree.ElementTree
是处理XML的一个常用模块。
写入XML文件
import xml.etree.ElementTree as ET
# 创建根元素
root = ET.Element("data")
# 创建子元素并添加到根元素
name = ET.SubElement(root, "name")
name.text = "John Doe"
age = ET.SubElement(root, "age")
age.text = "30"
# 创建树并写入文件
tree = ET.ElementTree(root)
with open('data.xml', 'wb') as file:
tree.write(file, encoding='utf-8', xml_declaration=True)
读取XML文件
# 解析XML文件
tree = ET.parse('data.xml')
root = tree.getroot()
# 遍历并打印元素
for child in root:
print(child.tag, child.text)
4. 读写INI文件
Python的configparser
模块用于处理INI文件。
写入INI文件
import configparser
# 创建ConfigParser对象
config = configparser.ConfigParser()
# 添加section
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
# 写入文件
with open('example.ini', 'w') as configfile:
config.write(configfile)
读取INI文件
# 读取INI文件
config = configparser.ConfigParser()
config.read('example.ini')
# 访问数据
print(config['DEFAULT']['ServerAliveInterval'])
print(config['bitbucket.org']['User'])
以上代码展示了如何在Python中处理txt、json、xml和ini文件的基本读写操作。每种文件格式都有其特定的用途和优势,选择哪种格式取决于你的具体需求。