Python教程(十九):文件操作(python操作文件夹)
nanshan 2025-07-28 19:15 5 浏览 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编程中的基础技能,掌握这些知识将让您能够处理各种文件相关的任务!
相关推荐
- 轻量级分析利器再升级:解读 DuckDB 1.3.0 新特性
-
DuckDB团队近日正式发布了最新版本——DuckDB1.3.0,代号“Ossivalis”。此次版本以金眼鸭的远古祖先BucephalaOssivalis命名,象征项目在演化和成长过...
- C++跨平台编译的终极奥义:用Docker把环境差异按在地上摩擦
-
"代码在本地跑得飞起,一上服务器就coredump?"——每个C++程序员都经历过的《编译器的复仇》事件!大家好,我是Henry,废话少说,今天来简单谈一下跨平台编译的那些事儿,...
- 全网最全-Version Script以及__asm__((".symver xxx"))使用总结
-
首先提醒一点,一切的前提建立在你的名字必须要mangling,不然无论你写的versionscript还是__asm__都不会起任何效果VersionScript简单用法:这是一个典型例子,这个例...
- Ubuntu 25.04 Beta发布:Linux 6.14内核
-
IT之家3月28日消息,Canonical昨日(3月27日)放出了Beta版Ubuntu25.04系统镜像,代号“PluckyPuffin”,稳定版预估将于2025年...
- 不同平台CRT的区别?什么是UCRT?如何看libc源代码?
-
若文章对您有帮助,欢迎关注程序员小迷。助您在编程路上越走越好!CRT运行时库C标准规定例如输入输出函数、字符串函数、内存操作等接口,一般采用C运行时库实现。微软的CRT微软有两套CRT,早期的MS...
- 信创力量,中兴绽放——中兴新支点桌面操作系统安装与使用全攻略
-
原文链接:「链接」Hello,大家好啊,今天给大家带来一篇中兴新支点桌面操作系统安装使用的文章,欢迎大家分享点赞,点个在看和关注吧!中兴新支点桌面操作系统是一款基于Linux内核、面向政企和信创环...
- Linux下安装常用软件都有哪些?做了一个汇总列表,你看还缺啥?
-
1.安装列表MySQL5.7.11Java1.8ApacheMaven3.6+tomcat8.5gitRedisNginxpythondocker2.安装mysql1.拷贝mysql安装文件到...
- 一篇文章解决Linux系统安全问题排查,另配实操环境
-
实操地址:https://www.skillup.host/1/linux/safe/command.md#Linux安全检查排查指南##1.系统账户安全检查###1.1检查异常账户``...
- 程序员必备的学习笔记《TCP/IP详解(一)》
-
为什么会有TCP/IP协议在世界上各地,各种各样的电脑运行着各自不同的操作系统为大家服务,这些电脑在表达同一种信息的时候所使用的方法是千差万别。就好像圣经中上帝打乱了各地人的口音,让他们无法合作一样...
- 《Linux常用命令》(linux的常用命令总结)
-
一、文件与目录操作1.目录导航pwd:显示当前工作目录路径示例:pwd关键词:当前路径、工作目录cd:切换目录示例:cd/home/user#切换到绝对路径cd..#...
- Kubernetes 教程之跟着官方文档从零搭建 K8S
-
前言本文将带领读者一起,参照者Kubernetes官方文档,对其安装部署进行讲解.Kubernetes更新迭代很快,书上、网上等教程可能并不能适用于新版本,但官方文档能.阅读这篇文章你...
- 电脑网卡坏了怎么修复(电脑网卡坏了怎么修复win7系统)
-
当电脑网卡出现故障时,无论是有线网络还是无线网络,都可能无法正常连接。下面从软件、硬件等方面,分步骤为你介绍排查与修复的解决方案。一、初步排查:锁定问题源头检查网络环境将手机、平板等其他设备连接至同一...
- 如何查询电脑/手机的物理地址(如何找手机的物理地址)
-
一、要查询电脑的物理地址(也称为MAC地址),可以按照以下步骤进行操作:1.打开命令提示符(Windows)或终端(Mac):-在Windows上,点击“开始”按钮,搜索“命令提示符”,然后点击打...
- IPv4 无网络访问权限全流程解决方案
-
当设备出现IPv4无网络访问权限问题时,多由网络配置错误、连接故障或服务异常导致。以下提供系统化的排查步骤与解决方案,帮助用户快速定位并修复问题。一、基础故障快速检查1.物理连接确认有线网络:检...
- Python教程(十九):文件操作(python操作文件夹)
-
昨天,我们学习了列表推导式,掌握了Python中最优雅的数据处理方式。今天,我们将学习文件操作—Python中读写文件的基础技能。文件操作是编程中的核心技能,无论是读取配置文件、保存用户数据,还是...
你 发表评论:
欢迎- 一周热门
-
-
UOS服务器操作系统防火墙设置(uos20关闭防火墙)
-
极空间如何无损移机,新Z4 Pro又有哪些升级?极空间Z4 Pro深度体验
-
手机如何设置与显示准确时间的详细指南
-
NAS:DS video/DS file/DS photo等群晖移动端APP远程访问的教程
-
如何在安装前及安装后修改黑群晖的Mac地址和Sn系列号
-
如何修复用户配置文件服务在 WINDOWS 上登录失败的问题
-
一加手机与电脑互传文件的便捷方法FileDash
-
日本海上自卫队的军衔制度(日本海上自卫队的军衔制度是什么)
-
10个免费文件中转服务站,分享文件简单方便,你知道几个?
-
爱折腾的特斯拉车主必看!手把手教你TESLAMATE的备份和恢复
-
- 最近发表
-
- 轻量级分析利器再升级:解读 DuckDB 1.3.0 新特性
- C++跨平台编译的终极奥义:用Docker把环境差异按在地上摩擦
- 全网最全-Version Script以及__asm__((".symver xxx"))使用总结
- Ubuntu 25.04 Beta发布:Linux 6.14内核
- 不同平台CRT的区别?什么是UCRT?如何看libc源代码?
- 信创力量,中兴绽放——中兴新支点桌面操作系统安装与使用全攻略
- Linux下安装常用软件都有哪些?做了一个汇总列表,你看还缺啥?
- 一篇文章解决Linux系统安全问题排查,另配实操环境
- 程序员必备的学习笔记《TCP/IP详解(一)》
- 《Linux常用命令》(linux的常用命令总结)
- 标签列表
-
- linux 查询端口号 (58)
- docker映射容器目录到宿主机 (66)
- 杀端口 (60)
- yum更换阿里源 (62)
- internet explorer 增强的安全配置已启用 (65)
- linux自动挂载 (56)
- 禁用selinux (55)
- sysv-rc-conf (69)
- ubuntu防火墙状态查看 (64)
- windows server 2022激活密钥 (56)
- 无法与服务器建立安全连接是什么意思 (74)
- 443/80端口被占用怎么解决 (56)
- ping无法访问目标主机怎么解决 (58)
- fdatasync (59)
- 405 not allowed (56)
- 免备案虚拟主机zxhost (55)
- linux根据pid查看进程 (60)
- dhcp工具 (62)
- mysql 1045 (57)
- 宝塔远程工具 (56)
- ssh服务器拒绝了密码 请再试一次 (56)
- ubuntu卸载docker (56)
- linux查看nginx状态 (63)
- tomcat 乱码 (76)
- 2008r2激活序列号 (65)