python处理文件和字符串的高效技巧,不允许你还不知道
一、文件处理高效技巧
- 上下文管理器(with语句)
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
# 自动处理文件关闭,即使发生异常
- 大文件逐行读取
with open('large_file.txt', 'r') as f:
for line in f: # 内存友好方式
process(line)
- 高效写入多行
lines = [...] * 10000
with open('output.txt', 'w') as f:
f.writelines(lines) # 比循环write()更高效
- 内存映射文件(超大文件处理)
import mmap
with open('huge_file.bin', 'r+b') as f:
mm = mmap.mmap(f.fileno(), 0)
# 像操作内存一样操作文件
- Path对象(Python 3.4+)
from pathlib import Path
content = Path('file.txt').read_text()
Path('output.txt').write_text('Hello')
二、字符串处理高效技巧
- f-strings(Python 3.6+)
name = "Alice"
print(f"Hello, {name}!") # 最快格式化方式
- join()替代字符串拼接
parts = ['a'] * 1000
s = ''.join(parts) # 比 += 快得多
- 字符串驻留(小字符串优化)
a = 'hello'
b = 'hello'
print(a is b) # True - Python自动驻留小字符串
- 高效分割/连接
import re
re.split(r'\s+', text) # 复杂分割比str.split()更快
- 字符串视图(memoryview)
data = b'large binary data'
mv = memoryview(data)
slice = mv[1000:2000] # 不创建新副本
三、文件与字符串结合技巧
- 生成器表达式处理大文件
with open('data.txt') as f:
nums = (int(line) for line in f)
total = sum(nums) # 内存高效
- 二进制文件与字符串转换
# 文本→二进制
data = "文本".encode('utf-8')
# 二进制→文本
text = data.decode('utf-8')
- 高效正则搜索大文件
import re
pattern = re.compile(r'pattern')
with open('large.txt') as f:
matches = (pattern.match(line) for line in f)
valid = filter(None, matches)
- 多文件处理
import fileinput
with fileinput.input(files=('a.txt', 'b.txt')) as f:
for line in f:
process(line)
- 使用StringIO/BytesIO
from io import StringIO, BytesIO
s = StringIO()
s.write('Hello')
print(s.getvalue())
四、性能关键技巧
- 编译正则表达式
import re
re_obj = re.compile(r'pattern') # 预编译
re_obj.search(text)
- 使用str.maketrans()进行批量字符替换
trans = str.maketrans('aeiou', '12345')
'apple'.translate(trans) # '1ppl2'
- 避免不必要的字符串拷贝
text = "large string"
sub = text[1000:2000] # Python会创建视图而非副本
- 使用format_map()处理动态模板
template = "{name} is {age} years old"
data = {'name': 'Alice', 'age': 30}
template.format_map(data)
- 利用lru_cache缓存字符串处理函数
from functools import lru_cache
@lru_cache(maxsize=1024)
def process_string(s):
# 复杂字符串处理
return result
记住:
- 小文件(<几MB):直接read()没问题
- 中等文件(几MB-几百MB):考虑逐行处理
- 大文件(>几百MB):考虑内存映射或特殊处理
- 字符串操作优先使用内置方法,它们是用C实现的
这些技巧能显著提升Python程序处理文件和字符串的效率,特别是在数据量大的场景下。