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

116 阅读3分钟

小伙伴们,欢迎来到 Python 世界!不管你是刚入门的新手,还是想提升技能的开发者,这篇指南都会带你深入浅出地了解 Python 特性,从处理大型数据文件到写出简洁高效可复用的代码。

第一部分:Python 文件处理

1. 基本文件操作

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

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

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

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

为何选用 with

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

2. 读写文件

逐行读取文件:

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

写入文件:

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

追加内容至文件:

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

3. 处理大型文件

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

不妨采用这些高效技巧:

逐行读取(流式读取):

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

分块读取:

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

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

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

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

import pandas as pd

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

写入 CSV 文件:

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

处理 Excel 文件:

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

分块处理大型 CSV 文件:

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 密集型任务的利器)

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 密集型任务的完美选择)

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 密集型任务:

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 密集型任务:

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. 简单装饰器

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. 带参数的装饰器

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

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 函数

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

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

列表推导式

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

字典推导式

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

原文:www.yuque.com/fengjutian/… 《掌握 Python 文件处理、并行处理和装饰器》