脚本如何实现文件内容分割功能

wen 实用脚本 1

本文目录导读:

脚本如何实现文件内容分割功能

  1. Python 实现(按行数分割)
  2. Python 实现(按大小分割)
  3. Shell 命令实现
  4. 更完善的 Python 版本
  5. 使用示例
  6. 高级功能:合并文件

Python 实现(按行数分割)

#!/usr/bin/env python3
import os
def split_file_by_lines(input_file, lines_per_file=1000):
    """按行数分割文件"""
    with open(input_file, 'r', encoding='utf-8') as f:
        file_count = 1
        line_count = 0
        output_file = None
        for line in f:
            # 每lines_per_file行创建新文件
            if line_count % lines_per_file == 0:
                if output_file:
                    output_file.close()
                base_name = os.path.splitext(input_file)[0]
                output_file = open(f"{base_name}_part{file_count}.txt", 'w', encoding='utf-8')
                file_count += 1
            output_file.write(line)
            line_count += 1
        if output_file:
            output_file.close()
# 使用示例
split_file_by_lines('large_file.txt', 500)

Python 实现(按大小分割)

#!/usr/bin/env python3
import os
import math
def split_file_by_size(input_file, chunk_size_mb=10):
    """按文件大小分割"""
    chunk_size = chunk_size_mb * 1024 * 1024  # 转换为字节
    file_size = os.path.getsize(input_file)
    num_chunks = math.ceil(file_size / chunk_size)
    with open(input_file, 'rb') as f:
        for i in range(num_chunks):
            base_name = os.path.splitext(input_file)[0]
            ext = os.path.splitext(input_file)[1]
            output_file = f"{base_name}_part{i+1}{ext}"
            with open(output_file, 'wb') as out:
                out.write(f.read(chunk_size))
# 使用示例
split_file_by_size('large_file.txt', 5)  # 5MB每份

Shell 命令实现

按行数分割

# 每1000行分割为一个文件
split -l 1000 large_file.txt part_
# 使用数字后缀
split -l 1000 -d large_file.txt part_
# 指定后缀长度和前缀
split -l 1000 -d -a 3 large_file.txt part_

按大小分割

# 每10MB分割为一个文件
split -b 10M large_file.txt part_
# 使用数字后缀
split -b 10M -d large_file.txt part_

更完善的 Python 版本

#!/usr/bin/env python3
import os
import sys
import argparse
def split_file(input_file, mode='lines', chunk_size=1000, output_prefix=None):
    """
    文件分割函数
    :param input_file: 输入文件路径
    :param mode: 分割模式 ('lines' 或 'size')
    :param chunk_size: 每块的大小(行数或MB)
    :param output_prefix: 输出文件前缀
    """
    if not os.path.exists(input_file):
        print(f"错误: 文件 {input_file} 不存在")
        return
    if output_prefix is None:
        output_prefix = os.path.splitext(input_file)[0] + "_part"
    ext = os.path.splitext(input_file)[1]
    if mode == 'lines':
        # 按行数分割
        with open(input_file, 'r', encoding='utf-8') as f:
            part_num = 1
            current_lines = 0
            for line in f:
                if current_lines == 0:
                    output_file = f"{output_prefix}{part_num:03d}{ext}"
                    out_f = open(output_file, 'w', encoding='utf-8')
                    print(f"创建文件: {output_file}")
                out_f.write(line)
                current_lines += 1
                if current_lines >= chunk_size:
                    out_f.close()
                    current_lines = 0
                    part_num += 1
            if current_lines > 0:
                out_f.close()
    elif mode == 'size':
        # 按大小分割(MB)
        chunk_bytes = chunk_size * 1024 * 1024
        with open(input_file, 'rb') as f:
            part_num = 1
            while True:
                chunk = f.read(chunk_bytes)
                if not chunk:
                    break
                output_file = f"{output_prefix}{part_num:03d}{ext}"
                with open(output_file, 'wb') as out_f:
                    out_f.write(chunk)
                print(f"创建文件: {output_file}")
                part_num += 1
    print(f"分割完成!原文件被分为 {part_num - 1} 个文件")
def main():
    parser = argparse.ArgumentParser(description='文件分割工具')
    parser.add_argument('input_file', help='要分割的文件路径')
    parser.add_argument('-m', '--mode', choices=['lines', 'size'], 
                       default='lines', help='分割模式')
    parser.add_argument('-n', '--number', type=int, default=1000,
                       help='每块的行数(lines模式)或大小MB(size模式)')
    parser.add_argument('-p', '--prefix', help='输出文件前缀')
    args = parser.parse_args()
    split_file(args.input_file, args.mode, args.number, args.prefix)
if __name__ == "__main__":
    main()

使用示例

# 使用shell命令
split -l 5000 -d data.txt chunk_
# 使用Python脚本(按行数)
python splitter.py -m lines -n 2000 data.txt
# 使用Python脚本(按大小)
python splitter.py -m size -n 5 data.txt
# 指定输出前缀
python splitter.py -m lines -n 1000 -p "output_" data.txt

高级功能:合并文件

#!/usr/bin/env python3
import glob
import os
def merge_files(pattern, output_file):
    """合并分割的文件"""
    files = sorted(glob.glob(pattern))
    if not files:
        print(f"没有找到匹配的文件: {pattern}")
        return
    with open(output_file, 'wb') as out_f:
        for file in files:
            print(f"合并文件: {file}")
            with open(file, 'rb') as in_f:
                out_f.write(in_f.read())
    print(f"合并完成!输出文件: {output_file}")
# 使用示例
merge_files('chunk_*.txt', 'merged_file.txt')

选择哪种方式取决于你的具体需求:

  • 简单分割:使用 shell 的 split 命令
  • 需要自定义逻辑:使用 Python 脚本
  • 大文件处理:建议使用二进制模式读取,提高效率

抱歉,评论功能暂时关闭!