掌握 Python 文件处理、并行处理和装饰器

简介: 本文介绍了 Python 在文件处理、并行处理以及高级功能(如装饰器、Lambda 函数和推导式)的应用。第一部分讲解了文件的基本操作、读写方法及处理大型文件的技巧,并演示了使用 Pandas 处理结构化数据的方式。第二部分探讨了多线程与多进程的并行处理,以及 `concurrent.futures` 模块的简化用法,适合不同类型的任务需求。第三部分则深入装饰器的实现与应用,包括简单装饰器、带参数的装饰器及 `functools.wraps` 的使用,同时简要介绍了 Lambda 函数和推导式的语法与场景。内容实用且全面,帮助读者掌握 Python 高效编程的核心技能。

第一部分:Python 文件处理

1. 基本文件操作

Python 内置的 open() 函数让文件操作变得格外轻松。以下是一种简单的打开、读取和关闭文件的方法:

python

体验AI代码助手

代码解读

复制代码

file = open("sample.txt", "r")
content = file.read()
file.close()

但还有更优的方式 —— 引入 with 语句

python

体验AI代码助手

代码解读

复制代码

with open("sample.txt", "r") as file:
    content = file.read()

为何选用 with

  • 它能自动关闭文件
  • 避免内存泄漏和文件锁定问题
  • 代码更整洁、更符合 Python 风格

2. 读写文件

逐行读取文件:

python

体验AI代码助手

代码解读

复制代码

with open("sample.txt", "r") as file:
    lines = file.readlines()

写入文件:

python

体验AI代码助手

代码解读

复制代码

with open("output.txt", "w") as file:
    file.write("Hello, world!")

追加内容至文件:

python

体验AI代码助手

代码解读

复制代码

with open("output.txt", "a") as file:
    file.write("\nNew line added!")

3. 处理大型文件

试图一次性加载超大文件?❌ 并非上策。

不妨采用这些高效技巧:

逐行读取(流式读取):

python

体验AI代码助手

代码解读

复制代码

with open("large_file.txt", "r") as file:
    for line in file:
        print(line.strip())

分块读取:

python

体验AI代码助手

代码解读

复制代码

with open("large_file.txt", "r") as file:
    while chunk := file.read(1024):
        print(chunk)

这样就能每次仅将文件的一小部分加载到内存中。

4. 使用 Pandas 处理 CSV 和 Excel 文件

要是你处理的是结构化数据,Pandas 就是你最好的帮手:

python

体验AI代码助手

代码解读

复制代码

import pandas as pd

df = pd.read_csv("data.csv")
print(df.head())

写入 CSV 文件:

python

体验AI代码助手

代码解读

复制代码

df.to_csv("output.csv", index=False)

处理 Excel 文件:

python

体验AI代码助手

代码解读

复制代码

df = pd.read_excel("data.xlsx", sheet_name="Sheet1")
df.to_excel("output.xlsx", index=False, sheet_name="Results")

分块处理大型 CSV 文件:

python

体验AI代码助手

代码解读

复制代码

chunk_size = 10000
for chunk in pd.read_csv("large_data.csv", chunksize=chunk_size):
    print(chunk.shape)

第二部分:Python 并行处理

想在更短时间内完成更多任务?通过并行充分利用 CPU 和 I/O。

1. 多线程(I/O 密集型任务的利器)

python

体验AI代码助手

代码解读

复制代码

import threading

def print_numbers():
    for i in range(5):
        print(i)

thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_numbers)

thread1.start()
thread2.start()
thread1.join()
thread2.join()

线程适用于以下任务:

  • 下载文件
  • 读写文件
  • 发起多个 API 调用

2. 多进程( CPU 密集型任务的完美选择)

python

体验AI代码助手

代码解读

复制代码

from multiprocessing import Pool

def square(n):
    return n * n

if __name__ == "__main__":
    with Pool(4) as p:
        result = p.map(square, [1, 2, 3, 4])
    print(result)

当你进行数据复杂计算时,就派上用场了。

3. concurrent.futures —— 简化的并行处理

对于 I/O 密集型任务:

python

体验AI代码助手

代码解读

复制代码

from concurrent.futures import ThreadPoolExecutor

def fetch_data(url):
    return f"Fetched {url}"

urls = ["https://site1.com", "https://site2.com"]
with ThreadPoolExecutor() as executor:
    results = executor.map(fetch_data, urls)
    print(list(results))

对于 CPU 密集型任务:

python

体验AI代码助手

代码解读

复制代码

from concurrent.futures import ProcessPoolExecutor

def cube(n):
    return n ** 3

with ProcessPoolExecutor() as executor:
    results = executor.map(cube, [1, 2, 3, 4])
    print(list(results))

第三部分:装饰器 —— Python 的超能力

装饰器能为函数增添额外行为。

1. 简单装饰器

python

体验AI代码助手

代码解读

复制代码

def my_decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

2. 带参数的装饰器

python

体验AI代码助手

代码解读

复制代码

def repeat(n):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(n):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def greet():
    print("Hello!")

3. 使用 functools.wraps

python

体验AI代码助手

代码解读

复制代码

import functools

def log(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args}")
        return func(*args, **kwargs)
    return wrapper

@log
def add(a, b):
    return a + b

print(add(2, 3))

functools.wraps 可保持原函数名称和文档字符串不变。

Lambda 函数

简洁的匿名函数,适合一行代码搞定的小任务。

python

体验AI代码助手

代码解读

复制代码

add = lambda x, y: x + y
print(add(5, 3))  # 8

列表推导式

python

体验AI代码助手

代码解读

复制代码

squares = [x ** 2 for x in range(5)]

字典推导式

python

体验AI代码助手

代码解读

复制代码

squares_dict = {x: x ** 2 for x in range(5)}


转载来源:https://juejin.cn/post/7500859352061444106

相关文章
|
1月前
|
测试技术 Python
Python装饰器:为你的代码施展“魔法”
Python装饰器:为你的代码施展“魔法”
228 100
|
2月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
255 101
|
1月前
|
缓存 Python
Python装饰器:为你的代码施展“魔法
Python装饰器:为你的代码施展“魔法
148 88
|
2月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
197 99
|
2月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
178 98
|
2月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
2月前
|
存储 缓存 测试技术
理解Python装饰器:简化代码的强大工具
理解Python装饰器:简化代码的强大工具
|
3月前
|
程序员 测试技术 开发者
Python装饰器:简化代码的强大工具
Python装饰器:简化代码的强大工具
206 92
|
2月前
|
缓存 测试技术 Python
解锁Python超能力:深入理解装饰器
解锁Python超能力:深入理解装饰器
110 2

推荐镜像

更多