0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

(複数文字コード対応版)ローカルフォルダを指定してUithub風テキストにしてくれるPythonコード

Posted at

動機

  • 以前の記事は、複数の文字コードのファイルを含むフォルダで使えなかったので対応
  • テキストが多い場合、表示に時間がかかっていたので省略

使い方(以前の変更点のみ)

  • encodings_to_try 変数に使用しそうな文字コードを設定する

ソースコード(Pythonファイル)

import os

# 処理する拡張子のリスト
target_extensions = ['.java', '.py', '.toml', '.md', '.xml', '.html', '.ts']

def write_tree(startpath, file_output, padding=""):
    
    # ディレクトリ内のすべてのファイルとフォルダをリスト
    items = sorted(os.listdir(startpath))

    for i, item in enumerate(items):
        # FULL Paths
        path = os.path.join(startpath, item)
        if os.path.isdir(path):
            # フォルダならばこれを出力して、再帰的に呼び出し
            file_output.write(f"{padding}|-- {item}/\n")
            write_tree(path, file_output, padding + "|   ")
        else:
            # ファイルならばこれを出力
            file_output.write(f"{padding}|-- {item}\n")

def list_files(startpath):
    file_paths = []
    for root, _, files in os.walk(startpath):
        for file in files:
            file_paths.append(os.path.join(root, file))
    return file_paths

def process_file(file_path, file_output, current_dir):
    relative_path = os.path.relpath(file_path, current_dir)
    separator = " | "
    encodings_to_try = ["utf-8", "cp932", "shift_jis"]

    for enc in encodings_to_try:
        try:
            with open(file_path, "r", encoding=enc) as f:
                
                counter = 1
                for line in f:
                    if counter == 1:
                        file_output.write("-----------------------------------------------------\n")
                        file_output.write(f"{relative_path}  (encoding: {enc})\n")
                        file_output.write("-----------------------------------------------------\n")
                    file_output.write(f"{counter}{separator}{line}")
                    counter += 1
                file_output.write("\n\n")
            break  # 成功したらループを抜ける
        except UnicodeDecodeError:
            continue
    else:
        # どのエンコーディングでも開けなかった場合
        file_output.write(f"!!! {relative_path} は開けませんでした。スキップします。\n\n")


def main():
    # 現在の作業ディレクトリを取得
    current_dir = os.getcwd()

    # フォルダ名の入力を促す
    foldername = input("フォルダ名を入力してください: ")

    # output.txtの初期化
    output_file = os.path.join(current_dir, "output.txt")
    with open(output_file, "w", encoding="utf-8") as file_output:
        file_output.write("\n\n")

        # フォルダの存在チェック
        if not os.path.exists(foldername):
            file_output.write("指定されたフォルダは存在しません。\n")
            print("指定されたフォルダは存在しません。")
            return

        file_output.write(f"{foldername}\n")

        # 指定されたフォルダのツリー構造を出力
        write_tree(foldername, file_output)

        file_output.write("\n\n")

        file_list = list_files(foldername)

        for file in file_list:
            if any(file.endswith(ext) for ext in target_extensions):
                process_file(file, file_output, "")

    # 入力待ち
    input("保存完了\n続行するには何かキーを押してください...")

if __name__ == "__main__":
    main()

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?