Python–文件的基础操作
1. 文件基础操作
1.1 文件读取
文本文件
# 方式1:二进制模式读取后解码
with open('info.txt', 'rb') as f:
data = f.read().decode('utf-8')
# 方式2:直接文本模式读取
with open('info.txt', 'rt', encoding='utf-8') as f:
data = f.read()
二进制文件(如图片)
with open('image.png', 'rb') as f:
image_data = f.read()
1.2 文件写入
文本写入
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!')
二进制写入
with open('image_copy.png', 'wb') as f:
f.write(image_data)
1.3 文件模式
模式 | 描述 | 示例 |
---|---|---|
r | 只读(默认) | open('file.txt') |
w | 写入(覆盖) | open('file.txt', 'w') |
a | 追加写入 | open('file.txt', 'a') |
b | 二进制模式 | open('image.png', 'rb') |
+ | 读写模式 | open('file.txt', 'r+') |
1.4 上下文管理
自动关闭文件,避免资源泄露
with open('file.txt', 'r') as f:
content = f.read()
1.5 路径处理
绝对路径与相对路径
import os
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, 'data', 'info.txt')
路径转义
# Windows路径需使用r或双反斜杠
path = r'C:\new\data.txt'
2. 常见文件格式处理
2.1 CSV文件
读取CSV
import csv
with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
写入CSV
with open('output.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age'])
writer.writerow(['Alice', 25])
2.2 INI配置文件
读取INI
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
value = config.get('section', 'key')
修改INI
config.add_section('new_section')
config.set('new_section', 'key', 'value')
with open('config.ini', 'w') as f:
config.write(f)
2.3 XML文件
解析XML
from xml.etree import ElementTree as ET
root = ET.parse('data.xml').getroot()
for child in root:
print(child.tag, child.attrib)
2.4 Excel文件
读取Excel
from openpyxl import load_workbook
wb = load_workbook('data.xlsx')
sheet = wb.active
print(sheet['A1'].value)
写入Excel
from openpyxl import Workbook
wb = Workbook()
sheet = wb.active
sheet['A1'] = 'Hello'
wb.save('output.xlsx')
2.5 压缩文件
压缩与解压
import shutil
shutil.make_archive('archive', 'zip', 'target_dir')
shutil.unpack_archive('archive.zip', 'extract_dir')
3. 实战练习
3.1 用户注册与登录(CSV)
import csv
import os
def register():
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, 'users.csv')
with open(file_path, 'a', newline='') as f:
writer = csv.writer(f)
username = input("用户名:")
password = input("密码:")
writer.writerow([username, password])
def login():
username = input("用户名:")
password = input("密码:")
with open('users.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
if row == [username, password]:
print("登录成功!")
return
print("登录失败!")
3.2 天气数据获取与写入Excel
import requests
from openpyxl import Workbook
city = input("请输入城市:")
url = f"http://api.example.com/weather?city={city}"
response = requests.get(url)
data = response.json()
wb = Workbook()
sheet = wb.active
sheet.append(["城市", "温度", "湿度"])
sheet.append([city, data['temp'], data['humidity']])
wb.save('weather.xlsx')
3.3 INI转Excel工具
from configparser import ConfigParser
from openpyxl import Workbook
config = ConfigParser()
config.read('config.ini')
wb = Workbook()
for section in config.sections():
sheet = wb.create_sheet(title=section)
sheet.append(["Key", "Value"])
for key, value in config.items(section):
sheet.append([key, value])
wb.save('config.xlsx')
作者:索然无味io