文件操作简介
什么是文件操作?
文件操作是程序与外部文件进行交互的过程,主要包括:
- 打开和关闭文件
- 读取文件内容
- 写入和修改文件
- 管理文件和目录
文件类型
- 文本文件:包含可读字符的文件(.txt, .py, .html等)
- 二进制文件:包含原始字节数据的文件(图片、音频等)
- 特殊文件:系统设备文件、管道等
打开和关闭文件
文件打开模式
- 'r':只读模式(默认)
- 'w':写入模式(会覆盖原文件)
- 'a':追加模式
- 'b':二进制模式
- 't':文本模式(默认)
- '+':读写模式
基本用法
# 推荐使用with语句(自动关闭文件)
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# 传统方式(需要手动关闭)
file = open('example.txt', 'r', encoding='utf-8')
try:
content = file.read()
print(content)
finally:
file.close()
注意事项
- 始终使用适当的字符编码(如UTF-8)
- 记得关闭文件(最好使用with语句)
- 正确处理文件不存在等异常情况
读取文件
读取方法
# 读取整个文件
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read() # 读取全部内容
print(content)
# 按行读取
with open('file.txt', 'r', encoding='utf-8') as f:
# 方法1:逐行读取
for line in f:
print(line.strip())
# 方法2:读取所有行到列表
lines = f.readlines()
for line in lines:
print(line.strip())
# 按字节读取
with open('file.txt', 'r', encoding='utf-8') as f:
chunk = f.read(100) # 读取100个字符
print(chunk)
读取技巧
- 大文件使用逐行读取或分块读取
- 使用strip()去除行尾换行符
- 注意文件指针的位置
写入文件
写入方法
# 写入字符串
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!\n') # 写入单行
f.write('这是第二行\n') # 写入中文
# 写入多行
lines = ['第一行\n', '第二行\n', '第三行\n']
with open('output.txt', 'w', encoding='utf-8') as f:
f.writelines(lines)
# 追加内容
with open('output.txt', 'a', encoding='utf-8') as f:
f.write('追加的内容\n')
# 格式化写入
name = "张三"
age = 25
with open('info.txt', 'w', encoding='utf-8') as f:
f.write(f"姓名:{name}\n年龄:{age}\n")
写入注意事项
- 'w'模式会覆盖原文件内容
- 写入换行符需要手动添加\n
- 确保写入的内容是字符串类型
目录操作
基本目录操作
import os
# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前目录:{current_dir}")
# 创建目录
os.mkdir('new_folder') # 创建单个目录
os.makedirs('path/to/new/folder') # 创建多级目录
# 删除目录
os.rmdir('empty_folder') # 删除空目录
# 列出目录内容
files = os.listdir('.') # 列出当前目录内容
print(f"目录内容:{files}")
# 判断路径
print(os.path.exists('file.txt')) # 检查文件是否存在
print(os.path.isfile('file.txt')) # 检查是否是文件
print(os.path.isdir('folder')) # 检查是否是目录
使用pathlib模块
from pathlib import Path
# 创建Path对象
path = Path('folder/subfolder/file.txt')
# 创建目录
path.parent.mkdir(parents=True, exist_ok=True)
# 文件操作
if not path.exists():
path.touch() # 创建空文件
# 遍历目录
for file in Path('.').glob('*.txt'):
print(f"找到文件:{file}")
# 路径操作
print(f"父目录:{path.parent}")
print(f"文件名:{path.name}")
print(f"扩展名:{path.suffix}")
实践练习
练习1:文件复制程序
def copy_file(source, destination):
try:
# 读取源文件
with open(source, 'r', encoding='utf-8') as src:
content = src.read()
# 写入目标文件
with open(destination, 'w', encoding='utf-8') as dst:
dst.write(content)
print(f"文件已从 {source} 复制到 {destination}")
except FileNotFoundError:
print("源文件不存在!")
except Exception as e:
print(f"复制过程中出错:{e}")
# 使用示例
copy_file('source.txt', 'destination.txt')
练习2:日志文件分析
def analyze_log(log_file):
error_count = 0
warning_count = 0
try:
with open(log_file, 'r', encoding='utf-8') as f:
for line in f:
if 'ERROR' in line:
error_count += 1
elif 'WARNING' in line:
warning_count += 1
print(f"分析结果:")
print(f"错误数量:{error_count}")
print(f"警告数量:{warning_count}")
except FileNotFoundError:
print("日志文件不存在!")
# 使用示例
analyze_log('app.log')