Python文件读写(txt、json、xml、ini)附详细代码讲解!

在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文件的基本读写操作。每种文件格式都有其特定的用途和优势,选择哪种格式取决于你的具体需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值