Python教程(十九):文件操作(文件 python)
off999 2025-07-19 21:58 38 浏览 0 评论
昨天,我们学习了列表推导式,掌握了Python中最优雅的数据处理方式。今天,我们将学习文件操作 — Python中读写文件的基础技能。
文件操作是编程中的核心技能,无论是读取配置文件、保存用户数据,还是处理日志文件,都离不开文件操作。
今天您将学习什么
- 文件操作的基本概念和模式
- 读取文件的多种方法
- 写入文件的技巧
- 文件路径和目录操作
- 真实世界示例:日志记录、配置管理、数据处理
什么是文件操作?
文件操作是指程序与计算机文件系统进行交互的过程,包括创建、读取、写入、修改和删除文件。
Python提供了内置的open()函数来处理文件操作,支持多种文件模式。
1. 文件操作基础
文件打开模式
# 基本语法
file = open(filename, mode)
# 常用模式
# 'r' - 读取模式(默认)
# 'w' - 写入模式(覆盖)
# 'a' - 追加模式
# 'x' - 独占创建模式
# 'b' - 二进制模式
# 't' - 文本模式(默认)基本文件操作流程
# 1. 打开文件
file = open('example.txt', 'r')
# 2. 操作文件
content = file.read()
# 3. 关闭文件
file.close()2. 读取文件
读取整个文件
# 方法1:基本读取
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
# 方法2:读取为列表(按行分割)
with open('example.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
print(line.strip()) # strip()去除换行符逐行读取
# 方法1:for循环
with open('example.txt', 'r', encoding='utf-8') as file:
for line in file:
print(line.strip())
# 方法2:readline()
with open('example.txt', 'r', encoding='utf-8') as file:
line = file.readline()
while line:
print(line.strip())
line = file.readline()读取指定字节数
with open('example.txt', 'r', encoding='utf-8') as file:
# 读取前100个字符
content = file.read(100)
print(content)3. 写入文件
覆盖写入
# 写入模式会覆盖原文件
with open('output.txt', 'w', encoding='utf-8') as file:
file.write("Hello, World!\n")
file.write("This is a test file.\n")
file.write("Python is awesome!")
print("文件写入完成!")追加写入
# 追加模式不会覆盖原文件
with open('output.txt', 'a', encoding='utf-8') as file:
file.write("\n\n这是追加的内容。")
file.write("\n文件操作很有趣!")
print("内容追加完成!")写入多行
lines = [
"第一行内容",
"第二行内容",
"第三行内容",
"第四行内容"
]
with open('multiline.txt', 'w', encoding='utf-8') as file:
file.writelines(line + '\n' for line in lines)
print("多行写入完成!")4. 文件路径操作
使用os模块
import os
# 获取当前工作目录
current_dir = os.getcwd()
print(f"当前目录:{current_dir}")
# 拼接路径
file_path = os.path.join(current_dir, 'data', 'example.txt')
print(f"文件路径:{file_path}")
# 检查文件是否存在
if os.path.exists(file_path):
print("文件存在")
else:
print("文件不存在")
# 获取文件信息
if os.path.exists(file_path):
file_size = os.path.getsize(file_path)
print(f"文件大小:{file_size} 字节")使用pathlib模块(推荐)
from pathlib import Path
# 创建Path对象
file_path = Path('data/example.txt')
# 检查文件是否存在
if file_path.exists():
print(f"文件存在,大小:{file_path.stat().st_size} 字节")
else:
print("文件不存在")
# 创建目录
file_path.parent.mkdir(parents=True, exist_ok=True)
# 读取文件
if file_path.exists():
content = file_path.read_text(encoding='utf-8')
print(content)真实世界示例1:日志记录系统
import datetime
from pathlib import Path
class Logger:
def __init__(self, log_file='app.log'):
self.log_file = Path(log_file)
self.log_file.parent.mkdir(parents=True, exist_ok=True)
def log(self, message, level='INFO'):
"""记录日志"""
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_entry = f"[{timestamp}] {level}: {message}\n"
with open(self.log_file, 'a', encoding='utf-8') as file:
file.write(log_entry)
def read_logs(self, lines=None):
"""读取日志"""
if not self.log_file.exists():
return []
with open(self.log_file, 'r', encoding='utf-8') as file:
if lines:
return file.readlines()[-lines:]
else:
return file.readlines()
def clear_logs(self):
"""清空日志"""
self.log_file.write_text('', encoding='utf-8')
# 使用示例
logger = Logger('logs/application.log')
# 记录一些日志
logger.log("应用程序启动")
logger.log("用户登录成功", "INFO")
logger.log("数据库连接失败", "ERROR")
logger.log("处理完成", "INFO")
# 读取最近的5行日志
recent_logs = logger.read_logs(5)
print("最近的日志:")
for log in recent_logs:
print(log.strip())真实世界示例2:配置管理系统
import json
from pathlib import Path
class ConfigManager:
def __init__(self, config_file='config.json'):
self.config_file = Path(config_file)
self.config = self.load_config()
def load_config(self):
"""加载配置文件"""
if self.config_file.exists():
try:
with open(self.config_file, 'r', encoding='utf-8') as file:
return json.load(file)
except json.JSONDecodeError:
print("配置文件格式错误,使用默认配置")
return self.get_default_config()
else:
print("配置文件不存在,创建默认配置")
default_config = self.get_default_config()
self.save_config(default_config)
return default_config
def save_config(self, config=None):
"""保存配置文件"""
if config is None:
config = self.config
with open(self.config_file, 'w', encoding='utf-8') as file:
json.dump(config, file, indent=2, ensure_ascii=False)
def get_default_config(self):
"""获取默认配置"""
return {
"database": {
"host": "localhost",
"port": 5432,
"name": "myapp"
},
"server": {
"host": "0.0.0.0",
"port": 8000,
"debug": True
},
"features": {
"enable_cache": True,
"enable_logging": True
}
}
def get(self, key, default=None):
"""获取配置值"""
keys = key.split('.')
value = self.config
for k in keys:
if isinstance(value, dict) and k in value:
value = value[k]
else:
return default
return value
def set(self, key, value):
"""设置配置值"""
keys = key.split('.')
config = self.config
for k in keys[:-1]:
if k not in config:
config[k] = {}
config = config[k]
config[keys[-1]] = value
self.save_config()
# 使用示例
config = ConfigManager('myapp_config.json')
# 获取配置值
db_host = config.get('database.host', 'localhost')
server_port = config.get('server.port', 8000)
print(f"数据库主机:{db_host}")
print(f"服务器端口:{server_port}")
# 设置配置值
config.set('database.host', '192.168.1.100')
config.set('features.enable_cache', False)
print("配置已更新")真实世界示例3:数据处理工具
import csv
from pathlib import Path
class DataProcessor:
def __init__(self, input_file, output_file):
self.input_file = Path(input_file)
self.output_file = Path(output_file)
def process_csv(self):
"""处理CSV文件"""
if not self.input_file.exists():
print(f"输入文件不存在:{self.input_file}")
return
processed_data = []
# 读取CSV文件
with open(self.input_file, 'r', encoding='utf-8', newline='') as file:
reader = csv.DictReader(file)
for row in reader:
# 处理每一行数据
processed_row = self.process_row(row)
if processed_row:
processed_data.append(processed_row)
# 写入处理后的数据
if processed_data:
self.write_csv(processed_data)
print(f"处理完成,共处理 {len(processed_data)} 行数据")
def process_row(self, row):
"""处理单行数据"""
# 示例:过滤空值,转换数据类型
processed = {}
for key, value in row.items():
if value and value.strip(): # 过滤空值
# 尝试转换为数字
try:
if '.' in value:
processed[key] = float(value)
else:
processed[key] = int(value)
except ValueError:
processed[key] = value.strip()
return processed if processed else None
def write_csv(self, data):
"""写入CSV文件"""
if not data:
return
# 确保输出目录存在
self.output_file.parent.mkdir(parents=True, exist_ok=True)
# 获取字段名
fieldnames = data[0].keys()
with open(self.output_file, 'w', encoding='utf-8', newline='') as file:
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(data)
# 创建示例CSV文件
def create_sample_csv():
sample_data = [
{'name': 'Alice', 'age': '25', 'score': '85.5'},
{'name': 'Bob', 'age': '30', 'score': '92.0'},
{'name': 'Charlie', 'age': '', 'score': '78.5'},
{'name': 'David', 'age': '28', 'score': '88.0'}
]
with open('sample_data.csv', 'w', encoding='utf-8', newline='') as file:
writer = csv.DictWriter(file, fieldnames=['name', 'age', 'score'])
writer.writeheader()
writer.writerows(sample_data)
print("示例CSV文件已创建")
# 使用示例
create_sample_csv()
processor = DataProcessor('sample_data.csv', 'processed_data.csv')
processor.process_csv()文件操作的最佳实践
推荐做法:
- 使用with语句自动管理文件
- 指定正确的编码格式
- 使用pathlib处理路径
- 适当处理文件异常
避免的做法:
- 忘记关闭文件
- 不处理文件不存在的情况
- 使用硬编码的文件路径
- 忽略编码问题
文件操作的高级技巧
二进制文件操作
# 复制文件
def copy_file(source, destination):
with open(source, 'rb') as src:
with open(destination, 'wb') as dst:
dst.write(src.read())
# 读取图片文件信息
def get_file_info(file_path):
with open(file_path, 'rb') as file:
content = file.read()
return {
'size': len(content),
'first_bytes': content[:10]
}临时文件操作
import tempfile
import os
# 创建临时文件
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
temp_file.write("临时数据")
temp_path = temp_file.name
# 使用临时文件
print(f"临时文件路径:{temp_path}")
# 清理临时文件
os.unlink(temp_path)回顾
今天您学习了:
- 文件操作的基本概念和模式
- 读取文件的多种方法
- 写入文件的技巧
- 文件路径和目录操作
- 真实世界应用:日志记录、配置管理、数据处理
文件操作是Python编程中的基础技能,掌握这些知识将让您能够处理各种文件相关的任务!
相关推荐
- 笔记本电脑系统修复软件(笔记本电脑程序修复)
-
1、超级兔子2013系统修复软件超级兔子是一款完整的系统维护工具。拥有电脑系统评测、垃圾清理和注册表清理、可疑文件和插件检测、网页防护等功能,同时自带一些实用的系统工具,可清理你大多数的文件、注册表里...
- 联想保修服务包括哪些(联想保修都保修什么)
-
1、保修36个月的硬件包括:CPU、内存。2、保修24个月的硬件包括:主板、显卡、LCD屏、硬盘、电源适配器、键盘、鼠标模块。3、保修12个月的硬件包括:LCD之附件、光驱、DVD、CDR/W、软驱...
- 系统科学大会(中国系统科学学会)
-
2021年各种科学大会的召开时间取决于疫情的发展和国家政策的调整。一些大型的国际科学会议可能会推迟或者采用线上形式进行,以保障参会人员的安全和健康。同时,一些国内的学术会议也会受到疫情的影响,需要推迟...
- win10系统下载的内容在哪(win10下载的软件在哪个文件夹)
-
进入C:\Windows\SoftwareDistribution\Download目录下,通过win10应用商店中下载的安装包都放在此目录下。进入C:\Windows\SoftwareDistrib...
- 下载原版xp系统光盘(xp光盘系统安装教程怎么安装)
-
方法步骤步骤如下:1、首先打开计算机,在电脑光驱上放入XP光盘,启动电脑后不停按F12、F11、Esc等启动热键,在弹出的启动菜单中选择DVD选项,回车。2、进入光盘主菜单,按数字2或点击选项2运行w...
- windows7中文版下载安装(windows7安装包下载)
-
谢邀,如果你戳设置-时间和语言-区域和语言,右边的语言提示“只允许使用一种语言包”,那么你的系统就是家庭中文版。家庭中文版限定系统界面只能使用简体中文显示,其他功能则与普通家庭版没有区别,也可以使用其...
- win7开机按f2怎么重装系统(win7开机按f12怎么重装系统)
-
开机或重启时,在进入Windows前按F2进入BIOS。 ←→移动到第三个好像是BOOT。 然后将EXTENELBOOT选项设置为ENABLE 最后按F5将第一启动项目设置为EXTENEL...
-
- win10驱动管理(win10驱动程序)
-
win10由于联网后会自动安装驱动,如果自动安装驱动没出现问题,即可视为最佳驱动,若出现问题,卸载出问题的驱动,然后去查自己主板型号,在主板供应商官网下载对应驱动即是最佳01Windows10驱动更新调整当前当你插入连接即插即用(Pn...
-
2025-12-29 05:51 off999
- 手机上怎么找qq邮箱登录(用手机怎么找到qq邮箱)
-
入口是“联系人”选项卡。qq邮箱手机在QQ主菜单中选择下方的“联系人”选项卡;3、在“联系人”中选取“公众号”选项卡;4、在公众号中菜单中找到或搜索“QQ邮箱提醒”,点击进入;5、点击“进入邮箱”;6...
- amd显卡控制面板
-
AMD显卡控制面板是用来管理你的AMD显卡的,可以在控制面板中进行设置一些简单的调整,来提升显卡性能和效果。1、先打开AMD控制面板。2、打开“垂直同步(V-SYNC)”功能,可调整细节,改善影像流畅...
- win10老是未响应卡死(window10总是未响应)
-
具体方法:1、如果win10中的应用程序出现不响应的情况,应该是应用程序加载失败了。可以通过重置方法来解决win10应用程序无响应。2、登录win10系统,用管理员身份运行Powershell(可在C...
- usb安装系统步骤(USB安装系统步骤)
-
1.准备一张U盘,将联想官网下载的系统镜像文件复制到U盘中;2.将U盘插入联想S41U电脑,重启电脑,按F12进入BIOS设置,将U盘设置为启动项;3.重启电脑,进入U盘安装界面,按提示操作,完成系统...
- win98安装教程(win98iso怎么安装)
-
如何安装windows98 一、具体安装步骤 备份好重要文件之后,就可以安装windows98了。 第一步:启动安装程序。 用户如果原来已安装了windows95/97/98,现在拟对其进行升...
- 雨林木风win7安装(雨林木风win732位安装教程)
-
安装步骤如下: 1、光盘放入光驱,复制光盘上的win7.gho和安装系统.exe到硬盘非C盘的文件夹;(gho文件名可以是其他名字,后缀为gho,体积最大的就是。) 2、双击安装系统.exe;...
- win10解绑管理员账户(win10管理员账户怎么取消开机密码)
-
要解除Windows10电脑上的管理员权限,您需要进行以下操作:1.打开“控制面板”:右键单击“开始”按钮,然后选择“控制面板”。2.进入“用户账户”:在控制面板中,选择“用户账户”。3.点击...
欢迎 你 发表评论:
- 一周热门
-
-
抖音上好看的小姐姐,Python给你都下载了
-
全网最简单易懂!495页Python漫画教程,高清PDF版免费下载
-
Python 3.14 的 UUIDv6/v7/v8 上新,别再用 uuid4 () 啦!
-
飞牛NAS部署TVGate Docker项目,实现内网一键转发、代理、jx
-
python入门到脱坑 输入与输出—str()函数
-
宝塔面板如何添加免费waf防火墙?(宝塔面板开启https)
-
Python三目运算基础与进阶_python三目运算符判断三个变量
-
(新版)Python 分布式爬虫与 JS 逆向进阶实战吾爱分享
-
失业程序员复习python笔记——条件与循环
-
系统u盘安装(win11系统u盘安装)
-
- 最近发表
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python封装 (57)
- python写入txt (66)
- python读取文件夹下所有文件 (59)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)
