Python 文件读写(txt、json、xml、ini)

2797 篇文章 2 订阅
2634 篇文章 14 订阅

在进行接口自动化测试时,我们经常需要处理各种格式的文件。熟练掌握对这些文件的读写能力对于提升测试效率至关重要。今天我们就来一起学习如何用Python来操作常见的文件类型,包括文本文件(.txt)、JSON文件(.json)、Excel文件(.xlsx)、XML文件(.xml)以及配置文件(.ini)。我们将通过具体的代码示例来了解如何进行读写操作,并特别关注文件的追加和覆盖模式。

文本文件(.txt)

1. 追加模式写入文本文件

# 追加模式写入
with open('example.txt', 'a') as file:
    file.write('\nHello, world!')
print("追加模式写入成功")

2. 覆盖模式写入文本文件

# 覆盖模式写入
with open('example.txt', 'w') as file:
    file.write('Hello, world!')
print("覆盖模式写入成功")

3. 读取文本文件

# 读取文件
with open('example.txt', 'r') as file:
    content = file.read()
print("文本文件内容:")
print(content)

JSON文件

4. 追加模式写入JSON文件

# 追加模式写入
data = {'name': 'John', 'age': 30}
with open('data.json', 'a') as file:
    # 需要先写入一个方括号开始
    if file.tell() == 0:
        file.write('[')
    import json
    json.dump(data, file)
    if file.tell() != 0:
        file.write(',\n')
print("追加模式写入成功")

5. 覆盖模式写入JSON文件

# 覆盖模式写入
data = {'name': 'John', 'age': 30}
with open('data.json', 'w') as file:
    json.dump(data, file)
print("覆盖模式写入成功")

6. 读取JSON文件

# 读取文件
with open('data.json', 'r') as file:
    data = json.load(file)
print("JSON文件内容:")
print(data)

Excel文件

7. 写入Excel文件

# 写入Excel文件
import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
df.to_excel('example.xlsx', index=False)
print("写入Excel文件成功")

8. 读取Excel文件

# 读取Excel文件
df = pd.read_excel('example.xlsx')
print("Excel文件内容:")
print(df)

XML文件

9. 追加模式写入XML文件

# 追加模式写入
from xml.etree.ElementTree import Element, SubElement, ElementTree
root = Element('root')
child = SubElement(root, 'item')
child.text = 'Sample Text'
# 检查文件是否为空
try:
    with open('example.xml', 'r') as file:
        pass
except IOError:
    # 如果文件不存在,则创建一个新的XML文件
    ElementTree(root).write('example.xml')
else:
    # 否则追加到现有的XML文件
    tree = ElementTree(file='example.xml')
    root = tree.getroot()
    new_child = SubElement(root, 'item')
    new_child.text = 'Another Text'
    tree.write('example.xml')
print("追加模式写入成功")

10. 读取XML文件

# 读取XML文件
tree = ElementTree(file='example.xml')
root = tree.getroot()
print("XML文件内容:")
for child in root:
    print(f'{child.tag}: {child.text}')

ini文件

11. 追加模式写入配置文件

# 追加模式写入
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}
with open('example.ini', 'a') as configfile:
    config.write(configfile)
print("追加模式写入成功")

12. 覆盖模式写入配置文件

# 覆盖模式写入
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}
with open('example.ini', 'w') as configfile:
    config.write(configfile)
print("覆盖模式写入成功")

13. 读取配置文件

# 读取配置文件
config = configparser.ConfigParser()
config.read('example.ini')
print("配置文件内容:")
print(config['DEFAULT']['Compression'])

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】

在这里插入图片描述

 ​​​​软件测试面试文档

我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值