0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pythonでのファイル分割

Posted at

環境

Python 3.11.0

参考

内容

大容量のcsvファイルを分割して保存する必要があったため
参考をもとに作成

file_section.py
input_file_name  = 'file_name.csv'
output_file_name = input_file_name.replace('.csv', '') + '_%d.csv'
file_encode = "utf-8"

# 1ファイルあたりの行数
line_max = 200
# 初期化
line_index = 1
file_seqno = 1

with open(input_file_name, 'r', encoding=file_encode) as in_file:
    line = in_file.readline()
    while line:  
        # line_maxに達したらファイル名(番号)更新
        if line_index > line_max:
            line_index = 1
            file_seqno += 1
        with open(output_file_name % file_seqno, 'a', encoding=file_encode) as out_file:
            line_index += 1
            out_file.write(line)
        line = in_file.readline()

実行するとこんな感じで出力されます
image.png

以上!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?