LoginSignup
1
3

os.walkを使ってフォルダ内のファイルの一覧表を作成

Posted at

Pythonによるフォルダ内のファイル一覧表の作成

特定のフォルダ内のドキュメントの情報をリスト化するためのPythonスクリプトをchatGPTで作成しました。os.walk()は特定のフォルダを一番深い階層まで探索できる関数です。今回紹介するコードで生成されるExcelシートには、フォルダ名、ファイル名、ハイパーリンク、最終編集日時、ファイルサイズ、ファイル拡張子の情報が含まれます。

前提条件

Document List Generatorスクリプトを実行するには、以下が必要です:

  • Python(バージョン3.x)
  • openpyxlライブラリ(pip install openpyxlコマンドでインストール)

コード

import os
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl import worksheet
from datetime import datetime

folder_path = '/path/to/your/folder'  # Replace with the actual folder path

# Create an empty list to store the document information
documents = []

# Get the total number of files
total_files = sum(len(files) for _, _, files in os.walk(folder_path))

# Iterate through the folders and files
for root, dirs, files in os.walk(folder_path):
    # Get the folder names
    folder_names = os.path.relpath(root, folder_path).split(os.path.sep)
    folder1 = folder_names[0] if len(folder_names) > 0 else ""
    folder2 = folder_names[1] if len(folder_names) > 1 else ""
    
    for file in files:
        # Get the filename
        filename = os.path.splitext(file)[0]
        
        # Get the full path to the document file
        document_path = os.path.join(root, file)
        
        # Create the hyperlink using the file path
        hyperlink = f'file://{document_path}'
        
        # Get the last editing date
        last_editing_date = datetime.fromtimestamp(os.path.getmtime(document_path)).strftime('%Y-%m-%d %H:%M')
        
        # Get the file size (in MB) with two decimal places
        file_size = round(os.path.getsize(document_path) / (1024 * 1024), 2)
        
        # Get the file extension
        file_extension = os.path.splitext(file)[1]
        
        # Append the document information as a tuple to the documents list
        documents.append((folder1, folder2, filename, hyperlink, last_editing_date, file_size, file_extension))
        
        # Print the progress with the corresponding file or folder being processed
        print(f"Processing: {os.path.join(root, file)}")
        print(f"Completed: {len(documents)}/{total_files}\n")

# Create a new workbook and select the active sheet
workbook = Workbook()
sheet = workbook.active

# Write headers to the first row
sheet.cell(row=1, column=1, value='Folder 1')
sheet.cell(row=1, column=2, value='Folder 2')
sheet.cell(row=1, column=3, value='Filename')
sheet.cell(row=1, column=4, value='Hyperlink')
sheet.cell(row=1, column=5, value='Last Editing Date')
sheet.cell(row=1, column=6, value='Filesize (MB)')
sheet.cell(row=1, column=7, value='File Extension')

# Write document information to subsequent rows
for idx, document in enumerate(documents, start=2):
    for col_idx, value in enumerate(document, start=1):
        sheet.cell(row=idx, column=col_idx, value=value)
    
    # Set the hyperlink format for the cell and set the filename as the display text
    cell = sheet.cell(row=idx, column=4)
    cell.value = document[2]
    cell.hyperlink = document[3]
    cell.style = "Hyperlink"

# Adjust column width to fit content
for column in sheet.columns:
    max_length = 0
    column_letter = get_column_letter(column[0].column)
    for cell in column:
        try:
            if len(str(cell.value)) > max_length:
                max_length = len(cell.value)
        except TypeError:
            pass
    adjusted_width = (max_length + 2) * 1.2
    sheet.column_dimensions[column_letter].width = adjusted_width

# Format Filesize column to display as MB with two decimal places
sheet.column_dimensions[get_column_letter(6)].number_format = '#,##0.00'

# Save the workbook to a file
workbook.save('/path/to/output.xlsx')  # Replace with the desired output file path

使用方法

  1. 好きなコードエディタでPythonスクリプトファイルを開きます。
  2. folder_path変数を、リストにしたいドキュメントが格納されているフォルダのパスに設定します。/path/to/your/folderを実際のフォルダパスに置き換えてください。r"path"のように先頭にrを付けるといいです。
  3. Pythonスクリプトを実行します。

出力

以下のカラムを持つExcelスプレッドシート(.xlsxファイル)を生成します:

  1. Folder 1:トップレベルのフォルダ名
  2. Folder 2:サブフォルダ名
  3. Filename:ドキュメントファイルの名前
  4. Hyperlink:ドキュメントファイルへのハイパーリンク。ハイパーリンクをクリックするとファイルが開きます。
  5. Last Editing Date:ドキュメントが最後に編集された日時。形式は「YYYY-MM-DD HH:MM」です。
  6. Filesize (MB):ドキュメントのファイルサイズをメガバイト(MB)単位で表示します。小数点以下2桁まで表示されます。
  7. File Extension:ドキュメントファイルの拡張子。

進行状況とステータス

スクリプトの実行中には、進行状況と対応するファイルやフォルダがコンソールに出力されます。これにより、進行状況を確認し、どのファイルやフォルダのデータが計算されているかを確認できます。

カスタマイズ

  • カラムを変更したり、順序を変更したりする場合は、コード内のカラム名とその対応する位置を更新します。
  • 出力ファイルのパスをカスタマイズするには、コード内の output_file_path 変数を更新します。

以下に、生成されるExcelスプレッドシートの例を示します:

Folder 1 Folder 2 Filename Hyperlink Last Editing Date Filesize (MB) File Extension
Root サブフォルダ1 ドキュメント1 ドキュメント1 2023-01-15 09:30 2.45 .docx
Root サブフォルダ1 ドキュメント2 ドキュメント2 2023-01-16 14:20 1.68 .pdf
Root サブフォルダ2 ドキュメント3 ドキュメント3 2023-01-17 17:45 0.78 .txt

上記の例は、説明用のものです。実際の生成されるスプレッドシートには、お使いのフォルダとドキュメントに固有の情報が含まれます。

さいごに

構造化されたデータであれば、正規表現でファイル名から情報抜き出したり、wordの情報を抜き出して、付け加えることもできます。

1
3
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
1
3