0
0

Python ツール #3 ― ファイルエンコーディングチェッカー

Last updated at Posted at 2024-04-30

Python ツール #3 ― ファイルエンコーディングチェッカー

「複数のファイルを読み込んで、それぞれのファイルの文字コードを 1つの Excel ファイルに書き出す」という処理の Python スクリプトを作成しました。

実行イメージ

入力ファイル
テスト用にさまざまな入力ファイルを用意しています。

Python_tool-FileEncodingChecker-Input.jpg

出力 Excel ファイル
ファイルを読み込んで、ファイル文字コードをチェックし、Excel ファイルに出力します。

Python_tool-FileEncodingChecker-Output.jpg

参考にしたソースコード

複数のフォルダーから複数のファイルを取り出すループから、このソースコードの関数を呼び出しているだけです...。

ソースコードの簡単な説明

  • 各定数値。必要に応じて修正してください。例えば、ファイルのパス “IN_SRC_ROOT” は、D: ドライブからの絶対パスでもよいですし、“file_encoding_checker.py” からの相対パスでもよいです。
    file_encoding_checker.py
    # Input, Output
    IN_DIR = '.\\input'
    OUT_DIR = '.\\output'
    # IN_SRC_ROOT = 'D:\\Developments\\PyCharmProjects\\tool-file_encoding_checker\\input'  # noqa
    IN_SRC_ROOT = '.\\input'
    IN_SRC_RELATIVE = '\\src'
    IN_EXCEL = IN_DIR + '\\file_encoding_checker_list_template.xlsx'
    OUT_EXCEL = OUT_DIR + '\\file_encoding_checker_list.xlsx'
    OUT_SHEET = 'File Encoding Checker List'
    IGNORE_EXTENDS = ['.dat', '.ini']
    OUT_DEBUG = OUT_DIR + '\\debug.txt'
    
  • ファイルエンコーディングのチェック関数。
    file_encoding_checker.py
    # Check File Encoding
    def check_file_encoding(full_path_file):
        detector = UniversalDetector()
        with open(full_path_file, mode='rb') as f:
            for binary in f:
                detector.feed(binary)
                if detector.done:
                    break
        detector.close()
        return detector.result, detector.result['encoding']
    
  • 複数のフォルダーから複数のファイルを取り出してチェック関数を呼び出すループの処理。
    file_encoding_checker.py
    # Seek Directories
    def seek_directories(write_excel: WriteExcel, level: int, dir_root: str, dir_relative: str, fp) -> None:
    
        dirs = []
        files = []
    
        for path in os.listdir(dir_root):
            if os.path.isfile(os.path.join(dir_root, path)):
                files.append(path)
            else:
                dirs.append(path)
    
        files.sort(key=str.lower)
        for file in files:
            base, ext = os.path.splitext(file)
            write_excel.write_cell(CELL_COL_NO, write_excel.get_count(), None, None, NUMBER_FORMAT)
            write_excel.write_cell(CELL_COL_PATH, dir_relative, ALIGN_LEFT_NO_WRAP, None, None)
            write_excel.write_cell(CELL_COL_FILE, file, ALIGN_LEFT_NO_WRAP, None, None)
            write_excel.write_cell(CELL_COL_EXT, ext, ALIGN_CENTER, None, None)
            # Ignore Files
            if (base.startswith('.') and ext == '') or ext in IGNORE_EXTENDS:
                atters = None
                encoding = None
            # Other Files
            else:
                atters, encoding = check_file_encoding(os.path.join(dir_root, file))
            if encoding is None:
                write_excel.write_cell(CELL_COL_ENCODING, '-', ALIGN_CENTER, None, None)
            else:
                write_excel.write_cell(CELL_COL_ENCODING, '%s' % encoding, ALIGN_LEFT_NO_WRAP, None, None)
            if atters is None:
                write_excel.write_cell(CELL_COL_ATTERS, '-', ALIGN_CENTER, None, None)
            else:
                write_excel.write_cell(CELL_COL_ATTERS, '%s' % atters, ALIGN_LEFT_NO_WRAP, None, None)
            print('%5d %s %s %s %s %s' %
                  (write_excel.get_count(), dir_relative, file, ext,
                   encoding if encoding is not None else '-', atters if atters is not None else '-'))
            fp.write('%5d %s %s %s %s %s\n' %
                     (write_excel.get_count(), dir_root, file, ext,
                      encoding if encoding is not None else '-', atters if atters is not None else '-'))
    
            write_excel.next_row()
    
        dirs.sort(key=str.lower)
        for dir_nest in dirs:
            seek_directories(write_excel, level + 1,
                             os.path.join(dir_root, dir_nest), os.path.join(dir_relative, dir_nest), fp)
    
        return
    

ソースコードの置き場所

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