Python File I/O: Reading and Writing Text, JSON, Excel, XML, and INI Files
This tutorial explains how to read and write common file formats in Python—including text, JSON, Excel, XML, and INI files—covering append, overwrite, and read operations with clear code examples for each file type.
When performing API automation testing, handling various file formats efficiently is essential. This guide demonstrates how to read and write common file types in Python, covering text (.txt), JSON (.json), Excel (.xlsx), XML (.xml), and configuration (.ini) files, with examples for append, overwrite, and read modes.
Text file (.txt)
1. Append mode:
# 追加模式写入
with open('example.txt', 'a') as file:
file.write('\nHello, world!')
print("追加模式写入成功")2. Overwrite mode:
# 覆盖模式写入
with open('example.txt', 'w') as file:
file.write('Hello, world!')
print("覆盖模式写入成功")3. Read file:
# 读取文件
with open('example.txt', 'r') as file:
content = file.read()
print("文本文件内容:")
print(content)JSON file (.json)
4. Append mode (write array elements incrementally):
# 追加模式写入
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. Overwrite mode:
# 覆盖模式写入
data = {'name': 'John', 'age': 30}
with open('data.json', 'w') as file:
json.dump(data, file)
print("覆盖模式写入成功")6. Read file:
# 读取文件
with open('data.json', 'r') as file:
data = json.load(file)
print("JSON文件内容:")
print(data)Excel file (.xlsx)
7. Write Excel file:
# 写入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. Read Excel file:
# 读取Excel文件
df = pd.read_excel('example.xlsx')
print("Excel文件内容:")
print(df)XML file (.xml)
9. Append mode (create or extend XML):
# 追加模式写入
from xml.etree.ElementTree import Element, SubElement, ElementTree
root = Element('root')
child = SubElement(root, 'item')
child.text = 'Sample Text'
# Check if file exists
try:
with open('example.xml', 'r') as file:
pass
except IOError:
# File does not exist, create new
ElementTree(root).write('example.xml')
else:
# Append to existing file
tree = ElementTree(file='example.xml')
root = tree.getroot()
new_child = SubElement(root, 'item')
new_child.text = 'Another Text'
tree.write('example.xml')
print("追加模式写入成功")10. Read XML file:
# 读取XML文件
tree = ElementTree(file='example.xml')
root = tree.getroot()
print("XML文件内容:")
for child in root:
print(f'{child.tag}: {child.text}')INI configuration file (.ini)
11. Append mode:
# 追加模式写入
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. Overwrite mode:
# 覆盖模式写入
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}
with open('example.ini', 'w') as configfile:
config.write(configfile)
print("覆盖模式写入成功")13. Read configuration file:
# 读取配置文件
config = configparser.ConfigParser()
config.read('example.ini')
print("配置文件内容:")
print(config['DEFAULT']['Compression'])Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.