新闻动态

Python编程高手都在用的10个文件处理技巧, 让你效率翻倍!

         发布日期:2025-08-07 08:06    点击次数:154

批量自动化处理:日均处理1000+文件时,可节省80%人工操作时间

跨平台兼容性:统一处理Windows/Linux/Mac文件路径问题

数据预处理基础:为数据分析/机器学习提供结构化数据输入

适用人群:掌握Python基础语法 (变量/循环/函数) ,具备文件读写基础操作经验的开发者

技巧① 智能路径拼接

使用os.path.join替代字符串拼接

示例:

import os

# 标准版

path = os.path.join("data", "2023", "logs.txt") # 输出: data\2023\logs.txt (Windows)

# 优化版 (Python 3.4+)

from pathlib import Path

path = Path("data") / "2023" / "logs.txt" # 自动适配系统路径分隔符

⚠️ 警告:直接使用+拼接路径可能导致跨平台异常

技巧② 上下文管理器

with语句自动释放资源

示例:

# 标准版

f = open("data.txt", "r")

content = f.read

f.close

# 优化版

with open("data.txt", "r") as f: # 文件在代码块结束后自动关闭

content = f.read

优势:防止文件句柄泄漏,建议100%使用

技巧③ 批量文件过滤

使用glob通配符匹配

示例:

import glob

# 匹配所有CSV文件

csv_files = glob.glob("data/*.csv")

# 递归搜索子目录

all_logs = glob.glob("**/*.log", recursive=True)

参数说明:*匹配任意字符,?匹配单个字符,[0-9]匹配数字范围

技巧④ 文件内容迭代

逐行处理大文件

示例:

with open("bigfile.txt", "r") as f:

for line in f: # 内存占用仅1行数据

process(line) # 自定义处理函数

性能对比:处理1GB文件时,逐行读取比readlines快3倍

技巧⑤ 二进制文件处理

使用rb/wb模式处理非文本文件

示例:

with open("image.png", "rb") as f: # 二进制模式

data = f.read

with open("copy.png", "wb") as f: # 写入二进制

f.write(data)

适用场景:图片/视频/加密文件传输

技巧⑥ 文件编码声明

显式指定编码格式

示例:

with open("chinese.txt", "r", encoding="utf-8") as f: # 指定编码

text = f.read

# 处理未知编码文件

import chardet

with open("unknown.txt", "rb") as f:

result = chardet.detect(f.read)

encoding = result['encoding']

常见编码:utf-8/gbk/latin-1

技巧⑦ 文件元信息

获取文件属性信息

示例:

import os

stat_info = os.stat("data.txt")

print(stat_info.st_size) # 文件大小

print(stat_info.st_mtime) # 最后修改时间

⏰ 时间戳转换:time.ctime(stat_info.st_ctime)

技巧⑧ 批量重命名

使用os.rename实现自动化

示例:

import os

for i, filename in enumerate(os.listdir):

if filename.endswith(".txt"):

new_name = f"log_{i:03d}.txt" # 001.txt格式

os.rename(filename, new_name)

改进方案:使用re模块实现正则表达式重命名

技巧⑨ 文件压缩处理

使用zipfile模块

示例:

import zipfile

# 创建压缩包

with zipfile.ZipFile("archive.zip", "w") as zipf:

zipf.write("data.txt")

# 解压文件

with zipfile.ZipFile("archive.zip", "r") as zipf:

zipf.extractall("extracted")

压缩加密:添加pwd=b"password"参数

技巧⑩内存映射文件

处理超大文件读取

示例:

import mmap

with open("huge.bin", "r+b") as f:

mm = mmap.mmap(f.fileno, 0) # 内存映射

print(mm.find(b"pattern")) # 快速查找

mm.close

适用场景:处理500MB+二进制文件

实战案例:日志文件分析

from collections import defaultdict

def analyze_logs(log_dir):

stats = defaultdict(int)

for log_file in glob.glob(f"{log_dir}/*.log"):

with open(log_file, "r") as f:

for line in f:

if"ERROR"in line:

stats["errors"] += 1

elif"WARNING"in line:

stats["warnings"] += 1

return dict(stats)

print(analyze_logs("server_logs"))

# 输出: {'errors': 127, 'warnings': 45}



 
友情链接:

Powered by 大小单双技巧死规律 @2013-2022 RSS地图 HTML地图