Pythonでファイル分割しよう

どうもいすいです。

前に紹介したPythonでテキストファイルを分割する方法のコードだけ紹介します。

詳しい解説は以下を参照ください。↓↓↓

コード紹介

import sys

count = 0
idx = 0

in_file = sys.argv[1]
num_file = int(sys.argv[2])
out_files = []

# 分割ファイルをリストに入れる
for i in range(num_file):
    out_files.append('{0}_{1}'.format(i+1, in_file))

# ファイルの行数をカウントし、countに入れる
with open(in_file, 'r', encoding='utf-8') as f:
    for line in f:
        count += 1

line_count = count / num_file
n = 0

# ファイルの総行数を表示する
print('line_count : {0}'.format(count))


#分割実行部分
with open(in_file, 'r', encoding='utf-8') as i:
    for out_file in out_files:
        f = open(out_file, 'w', encoding='utf-8')
        while True:
            line_i = i.readline()
        
            if idx <= line_count:
                f.writelines(line_i)
                print('now file : {0}, current line : {1} / {2}'.format(out_file, int(idx + n * line_count), count))
            else:
                idx = 0
                break
        
            idx += 1
        n += 1
        f.close()

あとはコマンドプロンプトなどで

python separate.py <分割したいファイル> <分割したい数>

などと入力して2~3分待てばOKです。

SNSでもご購読できます。

コメント

  1. wsbxdkmlkg より:

    Muchas gracias. ?Como puedo iniciar sesion?

wsbxdkmlkg へ返信する コメントをキャンセル

*