動機
- 以前の記事は、複数の文字コードのファイルを含むフォルダで使えなかったので対応
- テキストが多い場合、表示に時間がかかっていたので省略
使い方(以前の変更点のみ)
-
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()