Gaming Life

一日24時間、ゲームは10時間

Python 連番テキストファイルを結合する

test_0.txt, test_1.txt, test_2.txt, test_3.txt...と連番で用意したテキストファイルを順番通りに結合して、test.txtという一つのファイルとして書き出すプログラム。

import glob
import os.path


# ファイルの結合
def join_file(filePath):
    fileList = create_filelist(filePath)
    with open(filePath, 'wb') as saveFile:
        for f in fileList:
            data = open(f, "rb").read()
            saveFile.write(data)
            saveFile.flush()


# 連番ファイルのリスト作成
def create_filelist(filePath):
    pathList = []
    for index in range(100000):
        filename = file_indexed(filePath, index)
        # ファイルが存在しなければ終了
        if not os.path.exists(filename):
            break
        else:
            pathList.append(filename)

    return pathList


# ファイル名に指定のindex値をふる
def file_indexed(filePath, index):
    name, ext = os.path.splitext(filePath)

    return "{0}_{1}{2}".format(name, index, ext)


if __name__ == "__main__":
    join_file("testData/test.txt")  # 相対パス

まとめ

catでいいやん。