Python文件操作与数据处理实战指南!
Python文件操作与数据处理实战指南!
前言
文件操作与数据处理是Python编程中最基础也是最重要的技能之一。无论是数据分析、Web开发还是自动化脚本编写,都离不开对文件的读写和各种数据处理操作。本文将全面介绍Python中的文件操作方法和常用数据处理技巧,帮助开发者高效地处理各类数据任务。
一、Python基础文件操作
1.1 文件打开与关闭
Python使用内置的open()函数进行文件操作,基本语法如下:
1
|
file = open (filename, mode = 'r' , encoding = None ) |
常用模式参数:
‘r’:只读(默认)
‘w’:写入,会覆盖已有文件
‘a’:追加,在文件末尾添加
‘x’:独占创建,文件已存在则失败
‘b’:二进制模式
‘t’:文本模式(默认)
‘+’:更新(可读可写)
推荐使用上下文管理器(with语句):
1
2
3
|
with open ( 'example.txt' , 'r' , encoding = 'utf-8' ) as file : content = file .read() # 文件会在with块结束后自动关闭 |
1.2 文件读写方法
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# 写入文件 with open ( 'data.txt' , 'w' , encoding = 'utf-8' ) as f: f.write( '第一行内容\n' ) f.write( '第二行内容\n' ) f.writelines([ '第三行\n' , '第四行\n' ]) # 读取文件 with open ( 'data.txt' , 'r' , encoding = 'utf-8' ) as f: print (f.read()) # 读取全部内容 f.seek( 0 ) # 重置文件指针到开头 print (f.readline()) # 读取一行 f.seek( 0 ) print (f.readlines()) # 读取所有行到列表 |
二、常见文件格式处理
2.1 CSV文件处理
使用标准库csv:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import csv # 写入CSV文件 data = [ [ '姓名' , '年龄' , '城市' ], [ '张三' , 25 , '北京' ], [ '李四' , 30 , '上海' ] ] with open ( 'people.csv' , 'w' , newline = ' ', encoding=' utf - 8 ') as f: writer = csv.writer(f) writer.writerows(data) # 读取CSV文件 with open ( 'people.csv' , 'r' , encoding = 'utf-8' ) as f: reader = csv.reader(f) for row in reader: print (row) # 字典形式读写 with open ( 'people_dict.csv' , 'w' , newline = ' ', encoding=' utf - 8 ') as f: fieldnames = [ 'name' , 'age' , 'city' ] writer = csv.DictWriter(f, fieldnames = fieldnames) writer.writeheader() writer.writerow({ 'name' : '王五' , 'age' : 28 , 'city' : '广州' }) with open ( 'people_dict.csv' , 'r' , encoding = 'utf-8' ) as f: reader = csv.DictReader(f) for row in reader: print (row[ 'name' ], row[ 'age' ]) |
2.2 JSON文件处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import json # Python对象转JSON data = { "name" : "张三" , "age" : 25 , "hobbies" : [ "读书" , "游泳" ], "married" : False } # 写入JSON文件 with open ( 'data.json' , 'w' , encoding = 'utf-8' ) as f: json.dump(data, f, ensure_ascii = False , indent = 2 ) # 读取JSON文件 with open ( 'data.json' , 'r' , encoding = 'utf-8' ) as f: loaded_data = json.load(f) print (loaded_data[ 'name' ]) |
2.3 Excel文件处理(使用openpyxl)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
from openpyxl import Workbook, load_workbook # 创建Excel文件 wb = Workbook() ws = wb.active ws.title = "员工信息" # 写入数据 ws.append([ '姓名' , '部门' , '工资' ]) ws.append([ '张三' , '技术部' , 15000 ]) ws.append([ '李四' , '市场部' , 12000 ]) # 保存文件 wb.save( 'employees.xlsx' ) # 读取Excel文件 wb = load_workbook( 'employees.xlsx' ) ws = wb.active for row in ws.iter_rows(values_only = True ): print (row) |
三、高效数据处理技巧
3.1 使用Pandas进行数据处理
Pandas是Python中最强大的数据处理库之一,特别适合处理结构化数据。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import pandas as pd # 从CSV创建DataFrame df = pd.read_csv( 'people.csv' ) print (df.head()) # 基本数据处理 print (df.describe()) # 统计描述 print (df.sort_values( '年龄' , ascending = False )) # 排序 print (df[df[ '年龄' ] > 25 ]) # 条件筛选 # 数据清洗 df.dropna() # 删除空值 df.fillna( 0 ) # 填充空值 df[ '年龄' ] = df[ '年龄' ].astype( int ) # 类型转换 # 保存处理结果 df.to_excel( 'processed_data.xlsx' , index = False ) |
3.2 大数据文件处理策略
对于大文件,应避免一次性读取全部内容:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
# 逐行处理大文本文件 with open ( 'large_file.txt' , 'r' , encoding = 'utf-8' ) as f: for line in f: process_line(line) # 自定义处理函数 # 分块读取大CSV文件 chunk_size = 10000 for chunk in pd.read_csv( 'large_data.csv' , chunksize = chunk_size): process_chunk(chunk) # 使用生成器处理数据 def read_large_file(file_path): with open (file_path, 'r' , encoding = 'utf-8' ) as f: while True : data = f.read( 1024 ) # 每次读取1KB if not data: break yield data for chunk in read_large_file( 'very_large_file.txt' ): process_chunk(chunk) |
四、高级文件操作
4.1 目录遍历与文件操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import os from pathlib import Path # 使用os模块 print (os.listdir( '.' )) # 列出当前目录文件 os.makedirs( 'new_dir' , exist_ok = True ) # 创建目录 # 使用更现代的pathlib base_path = Path( '.' ) for file in base_path.glob( '*.txt' ): # 查找所有txt文件 print ( file .name, file .stat().st_size) # 文件名和大小 # 递归遍历目录 for root, dirs, files in os.walk( 'some_directory' ): for file in files: print (os.path.join(root, file )) |
4.2 文件压缩与解压
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import zipfile import gzip import shutil # ZIP文件处理 with zipfile.ZipFile( 'archive.zip' , 'w' ) as zf: zf.write( 'file1.txt' ) zf.write( 'file2.txt' ) with zipfile.ZipFile( 'archive.zip' , 'r' ) as zf: zf.extractall( 'extracted_files' ) # GZIP压缩 with open ( 'large_file.txt' , 'rb' ) as f_in: with gzip. open ( 'large_file.txt.gz' , 'wb' ) as f_out: shutil.copyfileobj(f_in, f_out) |
4.3 内存文件操作(StringIO/BytesIO)
1
2
3
4
5
6
7
8
9
10
11
12
|
from io import StringIO, BytesIO # 内存文本文件 string_io = StringIO() string_io.write( 'Hello ' ) string_io.write( 'World!' ) print (string_io.getvalue()) # Hello World! # 内存二进制文件 bytes_io = BytesIO() bytes_io.write(b 'binary data' ) print (bytes_io.getvalue()) |
五、实战案例:日志文件分析
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import re from collections import Counter def analyze_logs(log_file): # 统计IP访问次数 ip_pattern = re. compile (r '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' ) ip_counter = Counter() # 统计状态码 status_pattern = re. compile (r 'HTTP/1.\d" (\d{3})' ) status_counter = Counter() with open (log_file, 'r' , encoding = 'utf-8' ) as f: for line in f: # 提取IP ip_match = ip_pattern.search(line) if ip_match: ip_counter[ip_match.group()] + = 1 # 提取状态码 status_match = status_pattern.search(line) if status_match: status_counter[status_match.group( 1 )] + = 1 # 输出结果 print ( "Top 10 IPs:" ) for ip, count in ip_counter.most_common( 10 ): print (f "{ip}: {count}次" ) print ( "\n状态码统计:" ) for status, count in status_counter.most_common(): print (f "{status}: {count}次" ) # 使用示例 analyze_logs( 'web_server.log' ) |
六、最佳实践与注意事项
编码问题:
始终明确指定文件编码(推荐UTF-8)
处理不同编码文件时使用chardet检测编码
路径处理:
使用os.path.join()或pathlib构建跨平台路径
避免硬编码路径,使用配置文件或命令行参数
资源管理:
始终确保文件正确关闭(推荐使用with语句)
大文件处理时注意内存使用
错误处理:
捕获和处理文件操作可能抛出的异常(FileNotFoundError, PermissionError等)
实现重试机制处理临时性IO错误
性能优化:
批量读写优于单次操作
考虑使用内存映射文件处理超大文件
结语
Python提供了丰富而强大的文件操作和数据处理能力,从简单的文本文件到复杂的Excel表格,从基本的字符串处理到高级的数据分析,Python都能优雅地完成任务。掌握这些技能将大大提高您的开发效率和数据处理能力。
以上就是Python文件操作与数据处理实战指南的详细内容。
学习资料见知识星球。
以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。
快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利!
更多技巧, www.excelbook.cn
欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;
1、价值上万元的专业的PPT报告模板。
2、专业案例分析和解读笔记。
3、实用的Excel、Word、PPT技巧。
4、VIP讨论群,共享资源。
5、优惠的会员商品。
6、一次付费只需129元,即可下载本站文章涉及的文件和软件。
共有 0 条评论