20个超实用Python代码段(5) - 提升编程效率必备
- Python
- 2025-07-28
- 1917
20个超实用Python代码段(5)
提升编程效率必备技巧
引言
Python以其简洁优雅的语法和强大的功能库成为开发者最喜爱的语言之一。本文精选了20个实用Python代码段,涵盖文件操作、数据处理、网络请求等多个领域,帮助您在日常开发中提升效率。每个代码段都附有详细说明和使用示例,可直接应用到项目中。
1. 文件批量重命名
批量重命名目录下的所有文件,添加前缀或后缀:
import os
def batch_rename(directory, prefix='', suffix=''):
for filename in os.listdir(directory):
new_name = prefix + filename + suffix
os.rename(
os.path.join(directory, filename),
os.path.join(directory, new_name)
)
# 使用示例
batch_rename('/path/to/files', prefix='doc_', suffix='_v2')
2. 计算目录大小
递归计算目录的总大小(单位:MB):
import os
def get_dir_size(path):
total = 0
for entry in os.scandir(path):
if entry.is_file():
total += entry.stat().st_size
elif entry.is_dir():
total += get_dir_size(entry.path)
return total
# 使用示例
size_bytes = get_dir_size('/path/to/directory')
size_mb = round(size_bytes / (1024 * 1024), 2)
print(f"目录大小: {size_mb} MB")
3. 生成随机密码
生成包含大小写字母、数字和特殊字符的强密码:
import random
import string
def generate_password(length=12):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
# 使用示例
print("强密码:", generate_password(16))
4. 列表分块处理
将大列表分割为固定大小的块以便批量处理:
def chunk_list(lst, chunk_size):
for i in range(0, len(lst), chunk_size):
yield lst[i:i + chunk_size]
# 使用示例
data = list(range(1, 101)) # 1到100的列表
for chunk in chunk_list(data, 10):
print(f"处理分块: {chunk}")
5. 计算代码执行时间
使用装饰器测量函数执行时间:
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
print(f"{func.__name__} 执行时间: {end_time - start_time:.4f}秒")
return result
return wrapper
# 使用示例
@timing_decorator
def long_running_function():
time.sleep(2)
long_running_function()
6. 字典键值反转
反转字典的键和值(确保值唯一):
def invert_dict(d):
return {v: k for k, v in d.items()}
# 使用示例
original = {'a': 1, 'b': 2, 'c': 3}
inverted = invert_dict(original)
print("反转字典:", inverted)
7. 列表元素频率统计
统计列表中各元素出现的频率:
from collections import Counter
def frequency_count(lst):
return Counter(lst)
# 使用示例
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
freq = frequency_count(words)
print("元素频率:", freq.most_common())
8. 简单进度条
在循环中显示简单的文本进度条:
def progress_bar(current, total, bar_length=50):
percent = current / total
arrow = '=' * int(round(percent * bar_length) - 1) + '>'
spaces = ' ' * (bar_length - len(arrow))
print(f"\r进度: [{arrow + spaces}] {int(percent * 100)}%", end='', flush=True)
# 使用示例
items = range(0, 200)
for i, item in enumerate(items):
# 执行任务
progress_bar(i + 1, len(items))
print("\n完成!")
9. 文件内容搜索
在目录中递归搜索包含特定文本的文件:
import os
def search_files(directory, search_text):
found_files = []
for root, _, files in os.walk(directory):
for file in files:
file_path = os.path.join(root, file)
try:
with open(file_path, 'r', encoding='utf-8') as f:
if search_text in f.read():
found_files.append(file_path)
except Exception:
continue
return found_files
# 使用示例
results = search_files('/path/to/search', '重要内容')
print("找到的文件:", results)
10. 网页内容抓取
使用requests和BeautifulSoup抓取网页内容:
import requests
from bs4 import BeautifulSoup
def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取标题
title = soup.title.string if soup.title else '无标题'
# 提取所有段落
paragraphs = [p.get_text().strip() for p in soup.find_all('p')]
return {
'title': title,
'paragraphs': paragraphs
}
# 使用示例
data = scrape_website('https://example.com')
print("网页标题:", data['title'])
print("首段内容:", data['paragraphs'][0][:100] + '...')
11. JSON文件读写
简化JSON文件的读取和写入操作:
import json
def read_json(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
def write_json(data, file_path, indent=4):
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=indent)
# 使用示例
data = read_json('input.json')
data['new_key'] = '新值'
write_json(data, 'output.json')
12. 多线程任务执行
使用线程池并行处理任务:
from concurrent.futures import ThreadPoolExecutor
def process_item(item):
# 模拟耗时操作
import time
time.sleep(0.5)
return f"处理结果: {item}"
def parallel_processing(items, max_workers=4):
with ThreadPoolExecutor(max_workers=max_workers) as executor:
results = list(executor.map(process_item, items))
return results
# 使用示例
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
results = parallel_processing(items)
print("处理结果:", results[:3])
13. 环境变量管理
安全地获取和管理环境变量:
import os
def get_env_variable(name, default=None, required=True):
value = os.getenv(name, default)
if required and value is None:
raise ValueError(f"环境变量 {name} 未设置!")
return value
# 使用示例
db_host = get_env_variable('DB_HOST', 'localhost')
api_key = get_env_variable('API_KEY', required=True)
14. 列表扁平化处理
将嵌套的多层列表转换为单层列表:
def flatten_list(nested_list):
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(flatten_list(item))
else:
flattened.append(item)
return flattened
# 使用示例
nested = [1, [2, 3], [4, [5, 6]], 7]
flat = flatten_list(nested)
print("扁平化列表:", flat)
15. 日期范围生成
生成两个日期之间的所有日期:
from datetime import datetime, timedelta
def date_range(start_date, end_date):
current_date = start_date
while current_date <= end_date:
yield current_date
current_date += timedelta(days=1)
# 使用示例
start = datetime(2023, 1, 1)
end = datetime(2023, 1, 5)
for date in date_range(start, end):
print(date.strftime("%Y-%m-%d"))
16. 配置文件解析
解析INI格式的配置文件:
import configparser
def read_config(file_path):
config = configparser.ConfigParser()
config.read(file_path)
return config
# 使用示例
config = read_config('config.ini')
db_settings = {
'host': config.get('database', 'host'),
'port': config.getint('database', 'port'),
'user': config.get('database', 'user'),
'password': config.get('database', 'password')
}
print("数据库配置:", db_settings)
17. 数据缓存装饰器
创建简单的函数结果缓存机制:
from functools import lru_cache
@lru_cache(maxsize=128)
def expensive_calculation(n):
print(f"计算 {n}...")
# 模拟复杂计算
return n * n
# 使用示例
print(expensive_calculation(5)) # 首次计算
print(expensive_calculation(5)) # 从缓存获取
18. CSV文件读取
读取CSV文件并转换为字典列表:
import csv
def read_csv_to_dict(file_path):
with open(file_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
return [row for row in reader]
# 使用示例
data = read_csv_to_dict('data.csv')
print("CSV数据:", data[:2]) # 打印前两行
19. 文件路径处理
安全地构建文件路径并创建目录:
import os
def safe_file_path(base_dir, filename):
# 确保目录存在
os.makedirs(base_dir, exist_ok=True)
# 构建完整路径
full_path = os.path.join(base_dir, filename)
return full_path
# 使用示例
log_path = safe_file_path('logs/2023', 'app.log')
print("日志路径:", log_path)
20. 日志记录配置
快速配置标准日志记录功能:
import logging
def setup_logging(log_file='app.log', level=logging.INFO):
logging.basicConfig(
filename=log_file,
level=level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# 同时输出到控制台
console = logging.StreamHandler()
console.setLevel(level)
formatter = logging.Formatter('%(levelname)s: %(message)s')
console.setFormatter(formatter)
logging.getLogger().addHandler(console)
# 使用示例
setup_logging()
logging.info("应用程序启动")
logging.warning("配置未设置")
总结
这些Python代码段覆盖了日常开发中的常见任务,熟练掌握它们可以显著提升您的编程效率。建议将这些代码段保存到您的代码库中,并根据需要进行修改和扩展。持续学习和积累实用代码片段是成为高效开发者的重要途径。
本文由ZangYanBing于2025-07-28发表在吾爱品聚,如有疑问,请联系我们。
本文链接:https://liuhe.jltcw.com/20256712.html
发表评论