Python实现均匀拆分大文件

Python实现均匀拆分大文件

对于大文件业务中有时候需要进行均匀拆分后分别进行处理,这里用python实现了均匀拆分,设定拆分的目标文件数量,输入路径(必须是一个目录),会自动进行拆分

# -*- coding: utf-8 -*-
import math
import os
import shutil
import sys

# 获取运行脚本的当前目录
ROOT_PATH = os.path.abspath(os.path.join(sys.path[1], "..")) + os.sep
if os.sep == '\\':
  ROOT_PATH = 'C:\\Users\\yourusername\\Desktop\\'
FILE_SPLIT_NUM = 10  # 分割后的文件总量


def savelist(path, record, seq='\n', mode='w'):
  print('saving ' + path)
  with open(path, 'w') as f:
    f.write(seq.join(record))


# 对于大文件不会出现崩溃
def count_file_lines(path):
  print('count # reading ' + path)
  count = -1
  for count, line in enumerate(open(path, 'rU')):
    pass
  count += 1
  return count


def split_files(input_dir, file_name_prefix):
  output_dir = ROOT_PATH + "split"
  if os.path.exists(output_dir):
    shutil.rmtree(output_dir)  # 删除已存在目录
  os.makedirs(output_dir)
  print('input_dir:' + input_dir)
  print('output_dir:' + output_dir)

  total = sum([count_file_lines(input_dir + os.sep + filename) for filename in
               os.listdir(input_dir)])
  file_records_num = int(math.ceil(float(total) / FILE_SPLIT_NUM))

  cur_records_num = 0
  cur_records_list = []
  file_index = 0
  for filename in sorted(os.listdir(input_dir)):
    filepath = input_dir + os.sep + filename
    if os.path.isfile(filepath):
      with open(filepath) as f:
        print('reading # reading ' + filename)
        for line in f:
          cur_records_num += 1
          cur_records_list.append(line)
          if cur_records_num >= file_records_num:
            file_index += 1
            output_file = output_dir + os.sep + file_name_prefix + '_' + str(file_index)
            savelist(output_file, cur_records_list, '')
            cur_records_num = 0
            cur_records_list = []

  if cur_records_list and (total - file_index * file_records_num > 0):
    file_index += 1
    output_file = output_dir + os.sep + file_name_prefix + '_' + str(file_index)
    savelist(output_file, cur_records_list, '')


# argv[1]:input_path argv[2]:file_split_num argv[3]:file_name_prefix
if __name__ == '__main__':
  file_name_prefix = 'part'  # 拆分后的文件前缀
  if len(sys.argv) < 2:
    print('sys.argv length must great than 1')
    sys.exit(-1)
  input_path = sys.argv[1]
  if len(sys.argv) > 2:
    FILE_SPLIT_NUM = int(sys.argv[2])
  if len(sys.argv) > 3:
    file_name_prefix = int(sys.argv[3])
  split_files(input_path, file_name_prefix)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个Python实现的CSV文件拆分案例: 假设我们有一个名为“data.csv”的CSV文件,其中包含10万行数据。我们要将它拆分成10个文件,每个文件包含1万行数据。 ```python import os import csv # 源文件路径 input_file = 'data.csv' # 拆分后的文件夹路径 output_folder = 'output' # 每个文件包含的行数 rows_per_file = 10000 # 创建输出文件夹 if not os.path.exists(output_folder): os.mkdir(output_folder) # 读取源文件 with open(input_file, 'r') as f: # 使用csv模块读取csv文件 reader = csv.reader(f) # 跳过标题行 next(reader) # 初始化计数器和文件编号 count = 0 file_num = 1 # 创建第一个输出文件 output_file = os.path.join(output_folder, f'data_{file_num}.csv') with open(output_file, 'w', newline='') as f_out: writer = csv.writer(f_out) # 写入标题行 writer.writerow(['id', 'name', 'age']) # 遍历源文件中的每一行数据 for row in reader: # 写入当前行数据到输出文件 writer.writerow(row) # 计数器加1 count += 1 # 如果计数器达到指定的行数,创建一个新的输出文件 if count == rows_per_file: # 重置计数器 count = 0 # 增加文件编号 file_num += 1 # 创建新的输出文件 output_file = os.path.join(output_folder, f'data_{file_num}.csv') with open(output_file, 'w', newline='') as f_out: writer = csv.writer(f_out) # 写入标题行 writer.writerow(['id', 'name', 'age']) ``` 这个程序会读取“data.csv”文件中的数据,并将它们写入到多个输出文件中。每个输出文件包含指定数量的行数,最后一个文件可能会少于指定数量的行数。输出文件名的格式为“data_1.csv”,“data_2.csv”,以此类推。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值