在进行接口自动化测试时,我们经常需要处理各种格式的文件。熟练掌握对这些文件的读写能力对于提升测试效率至关重要。今天我们就来一起学习如何用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'])
友情链接: 黑马模板网