本文目录导读:

拆分大文本文件有多种方法,具体取决于你的需求和操作系统,以下是几种常见的方案:
Linux/Unix 命令行工具
使用 split 命令(最常用)
# 按行数拆分(每10000行一个文件) split -l 10000 large_file.txt output_prefix_ # 按文件大小拆分(每个文件100MB) split -b 100M large_file.txt output_prefix_ # 按行数拆分并保留原始扩展名 split -l 10000 large_file.txt output_ --additional-suffix=.txt
使用 csplit 命令(按内容拆分)
# 按正则表达式拆分
csplit large_file.txt /pattern/ {*}
Python 脚本
按行数拆分
#!/usr/bin/env python3
import os
def split_file_by_lines(input_file, lines_per_file=10000):
"""按行数拆分大文件"""
with open(input_file, 'r', encoding='utf-8') as f:
file_count = 1
current_lines = []
for line in f:
current_lines.append(line)
if len(current_lines) >= lines_per_file:
write_chunk(input_file, current_lines, file_count)
file_count += 1
current_lines = []
# 处理最后剩余的行
if current_lines:
write_chunk(input_file, current_lines, file_count)
def write_chunk(original_file, lines, chunk_num):
"""写入分片文件"""
base_name = os.path.splitext(original_file)[0]
output_file = f"{base_name}_part{chunk_num:04d}.txt"
with open(output_file, 'w', encoding='utf-8') as f:
f.writelines(lines)
print(f"Created: {output_file} ({len(lines)} lines)")
# 使用示例
split_file_by_lines('large_file.txt', lines_per_file=10000)
按文件大小拆分
#!/usr/bin/env python3
import os
import math
def split_file_by_size(input_file, chunk_size_mb=100):
"""按文件大小拆分"""
chunk_size_bytes = chunk_size_mb * 1024 * 1024
file_size = os.path.getsize(input_file)
num_chunks = math.ceil(file_size / chunk_size_bytes)
with open(input_file, 'rb') as f:
for i in range(num_chunks):
chunk_data = f.read(chunk_size_bytes)
base_name = os.path.splitext(input_file)[0]
output_file = f"{base_name}_part{i+1:04d}.txt"
with open(output_file, 'wb') as out:
out.write(chunk_data)
print(f"Created: {output_file} ({len(chunk_data)} bytes)")
# 使用示例
split_file_by_size('large_file.txt', chunk_size_mb=100)
Bash 脚本(跨平台)
#!/bin/bash
# 拆分大文本文件的 Shell 脚本
INPUT_FILE="large_file.txt"
LINES_PER_FILE=10000
PREFIX="split_part"
# 检查文件是否存在
if [ ! -f "$INPUT_FILE" ]; then
echo "Error: File $INPUT_FILE not found"
exit 1
fi
echo "Splitting $INPUT_FILE..."
# 获取总行数
TOTAL_LINES=$(wc -l < "$INPUT_FILE")
echo "Total lines: $TOTAL_LINES"
# 计算文件数量
NUM_FILES=$(( (TOTAL_LINES + LINES_PER_FILE - 1) / LINES_PER_FILE ))
echo "Will create $NUM_FILES files"
# 拆分文件
split -l $LINES_PER_FILE "$INPUT_FILE" "${PREFIX}_"
# 重命名文件
count=1
for file in ${PREFIX}_*; do
if [ -f "$file" ]; then
mv "$file" "${PREFIX}_$(printf %04d $count).txt"
echo "Created: ${PREFIX}_$(printf %04d $count).txt"
((count++))
fi
done
echo "Split complete!"
Windows PowerShell 脚本
# 按行数拆分
$inputFile = "large_file.txt"
$linesPerFile = 10000
$prefix = "split_part"
$stream = [System.IO.StreamReader]::new($inputFile)
$fileCount = 1
$lineCount = 0
$output = [System.IO.StreamWriter]::new("${prefix}_$( '{0:D4}' -f $fileCount).txt")
while ($stream.Peek() -ge 0) {
$line = $stream.ReadLine()
$output.WriteLine($line)
$lineCount++
if ($lineCount -ge $linesPerFile) {
$output.Close()
$fileCount++
$output = [System.IO.StreamWriter]::new("${prefix}_$( '{0:D4}' -f $fileCount).txt")
$lineCount = 0
}
}
$output.Close()
$stream.Close()
Write-Host "Created $fileCount files"
使用 awk 工具
# 每10000行拆分一个文件
awk 'NR%10000==1{x="filename_"++i".txt"}{print > x}' large_file.txt
大型文件内存优化版本
#!/usr/bin/env python3
import os
import sys
def chunk_file_read(input_file, chunks, chunk_size=4096):
"""内存友好的分块读取器"""
with open(input_file, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
yield chunk
def split_large_file_fast(input_file, lines_per_file=10000):
"""高效拆分大文件(优化版)"""
base_name = os.path.splitext(input_file)[0]
file_count = 1
line_count = 0
with open(input_file, 'r', encoding='utf-8') as f:
current_lines = []
for line in f:
current_lines.append(line)
line_count += 1
if line_count >= lines_per_file and len(current_lines) >= lines_per_file:
output_file = f"{base_name}_part{file_count:04d}.txt"
with open(output_file, 'w', encoding='utf-8') as out:
out.writelines(current_lines)
print(f"Written: {output_file}")
current_lines = []
line_count = 0
file_count += 1
# 处理最后剩余的行
if current_lines:
output_file = f"{base_name}_part{file_count:04d}.txt"
with open(output_file, 'w', encoding='utf-8') as out:
out.writelines(current_lines)
print(f"Written: {output_file} (final)")
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python split_file.py <input_file> [lines_per_file]")
sys.exit(1)
input_file = sys.argv[1]
lines_per_file = int(sys.argv[2]) if len(sys.argv) > 2 else 10000
split_large_file_fast(input_file, lines_per_file)
选择建议
| 方法 | 优点 | 适用场景 |
|---|---|---|
split 命令 |
最快、最简单 | Unix/Linux 系统 |
| Python 脚本 | 跨平台、灵活 | Windows/Linux/Mac |
| Bash 脚本 | 自动化方便 | Linux 系统 |
| PowerShell | Windows 集成 | Windows 系统 |
| awk | 轻量级 | Unix/Linux 快速任务 |
注意事项
- 编码问题:确保脚本和文件编码一致(UTF-8 通常最佳)
- 行结束符:Windows 使用
\r\n,Unix 使用\n - 内存管理:处理超大文件时使用逐行读取,避免一次性加载整个文件
- 文件命名:建议使用序列号命名,便于后续合并
- 数据完整性:拆分后检查行数和字节数是否匹配
选择最符合你环境的方法即可,如果文件特别大(>10GB),推荐使用 split 命令或优化后的 Python 版本。