今天,小哥给大家提供了丰富的文件读写功能,可应用于各种文件格式。本篇博客将总结Python中读写各类文件的方法,包括文本文件、CSV文件、JSON文件、Excel文件等。无论你是初学者还是有经验的开发者,这里都将为你提供一份全面的文件操作指南。
file_path = 'example.txt'
with open(file_path, 'r') as file:
content = file.read()
print(content)
file_path = 'example.txt'
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
file_path = 'output.txt'
with open(file_path, 'w') as file:
file.write('Hello, Python!\n')
file.write('This is a guide to file operations in Python.')
import csv
file_path = 'example.csv'
with open(file_path, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
import csv
file_path = 'output.csv'
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
with open(file_path, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
import csv
# 数据
data = [
{'Name': '小米', 'Age': 25, 'City': '北京'},
{'Name': '苹果', 'Age': 30, 'City': '加州'},
{'Name': '华为', 'Age': 28, 'City': '深圳'}
]
# CSV文件路径
file_path = 'output.csv'
# 写入CSV文件
with open(file_path, 'w', newline='') as file:
# 提取标题行
fieldnames = data[0].keys()
# 创建CSV写入对象
writer = csv.DictWriter(file, fieldnames=fieldnames)
# 写入标题行
writer.writeheader()
# 写入数据
writer.writerows(data)
print(f'CSV文件已成功写入:{file_path}')
import json
file_path = 'example.json'
with open(file_path, 'r') as file:
data = json.load(file)
print(data)
import json
file_path = 'output.json'
data = {'name': 'John', 'age': 28}
with open(file_path, 'w') as file:
json.dump(data, file)
pandas
库读取Excel文件import pandas as pd
file_path = 'example.xlsx'
df = pd.read_excel(file_path)
print(df)
pandas
库写入Excel文件import pandas as pd
file_path = 'output.xlsx'
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
df.to_excel(file_path, index=False)