Pythonでフォルダ内のファイル一覧CSVを作成するプログラム

日常業務でフォルダやファイルの整理は、時間を浪費してしまう作業の一つです。そこで、今回はPythonを使ったファイル管理の基本として、カレントフォルダ内のファイル一覧をCSVファイルに出力するプログラムを作成します。

プログラムの細かいことは、あまり気にしないで、まず実行してみてPythonの便利さを実感してください。なお、ここではWindows環境で説明します。

この記事の目次

準備(Pythonのインストール)

以下の記事を参考にWindowsにPythonをインストールしてください。

no image
Pythonに入門するには、パソコンにPythonをインストールするだけです。Pythonを始めるのは非常に簡単です。 Python公式のインストーラーがあるので、ダウンロードしてインストールす…

プログラミング

早速プログラミングします。以下の手順で実際に実行してください。

1. メニューからPythonのIDLEを開きます。

python idle select from menu

2. エディタを開いて、コードを貼り付ける

IDLEツールバーのメニューから File ▶ New File を選択してエディタを開いてください。

idle new editor

そこに、以下のプログラムコードをコピーして貼り付けてください。

import os
import csv
import time

csv_file = 'filelist.csv'
date_format = '%Y/%m/%d %H:%M:%S'

file_list = []

for file in os.listdir("."):
    # ファイルかどうか
    is_file = os.path.isfile(file)
    # このpyファイル自身でないか
    not_py_file = os.path.basename(__file__) != file
    # リストCSVファイルでないか
    not_csv_file = csv_file != file

    if is_file and not_py_file and not_csv_file:
        # ファイル作成時刻
        time_crt = time.strftime(date_format,
                                 time.localtime(os.path.getctime(file)))
        # ファイル更新時刻
        time_mod = time.strftime(date_format,
                                 time.localtime(os.path.getmtime(file)))

        file_list.append([file, time_crt, time_mod])

with open(csv_file, "w", newline="") as f:
    csv_writer = csv.writer(f)
    for r in file_list:
        csv_writer.writerow(r)

IDLEの新しいウィンドウ(エディタ)にプログラムを入力した様子は以下のようになります。

python editor copy code

3. コードの保存

IDLEのツールバーのメニューから File ▶ Save を選択して、listingfiles.pyという名前で適当なフォルダに保存します。

プログラムの実行

どんなファイルでも構わないので、5〜10程度の適当なファイルを、listingfiles.pyプログラムと同じフォルダににコピーします。

python idle select from menu

WindowsにPythonをインストールすると、拡張子がpyのPythonファイルはダブルクリックで実行できますので、listingfiles.pyダブルクリックしてください。

すると、以下のようにフォルダ内にfilelist.csvというファイルができます。

python idle select from menu

エクセルで開くと、以下のようにファイル一覧が保存されているのを確認できます。

python idle select from menu

その他の実行方法

以下のようにIDLEのツールバーのメニューから Run ▶ Run Module を選択してもプログラムを実行できます。

python idle select from menu

カスタマイズ例

今回は、以下の3項目を出力しましたが、さらに欲しい項目があれば追加できます。

  • ファイル名
  • ファイル作成日時
  • ファイル更新日時

例えば、ファイルサイズを追加するには以下のようにコードを改良します。

import os
import csv
import time

csv_file = 'filelist.csv'
date_format = '%Y/%m/%d %H:%M:%S'

file_list = []

for file in os.listdir("."):
    # ファイルかどうか
    is_file = os.path.isfile(file)
    # このpyファイル自身でないか
    not_py_file = os.path.basename(__file__) != file
    # リストCSVファイルでないか
    not_csv_file = csv_file != file

    if is_file and not_py_file and not_csv_file:
        # ファイル作成時刻
        time_crt = time.strftime(date_format,
                                 time.localtime(os.path.getctime(file)))
        # ファイル更新時刻
        time_mod = time.strftime(date_format,
                                 time.localtime(os.path.getmtime(file)))
        # ファイルサイズ -> 新規追加
        file_size = os.path.getsize(file)

        file_list.append([file, time_crt, time_mod, file_size])

with open(csv_file, "w", newline="") as f:
    csv_writer = csv.writer(f)
    for r in file_list:
        csv_writer.writerow(r)

この要領で、必要なファイル情報を組み合わせることができます。その他のファイル情報を取得するには、以下の表を参考にしてください。

ファイル情報 取得方法(プログラム) 解説
拡張子 os.path.splitext(filename)[1]
最後にアクセスした日時 os.path.getatime(filename) 日本時間で書式を指定して出力するために次のようにする
time.strftime(dateFormat,time.localtime(ここに書く)))
作成日時 os.path.getctime(filename)
最後に更新した日時 os.path.getmtime(filename)
フルパス os.path.abspath(filename) 例:C:¥User¥Taro¥Documents¥data.txt
サイズ os.path.getsize(filename) 単位はバイト