先日、Python のビルドインウェブサーバを立ち上げたので、指定ディレクトリ配下のファイル一覧を更新日降順で表示するページを用意しました。
初 Python コーディングなので愚直な書き方をしていると思います。
なお、CSS フレームワークに Pure.css を使用しています。(これも初)
Tables - Pure
If you prefer horizontal lines only, add the pure-table-horizontal classname to the<table>
element.
#!/usr/bin/python3
import os
import datetime
# header
print("Content-Type: text/html; charset=UTF-8\n")
print("<link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/purecss@3.0.0/build/pure-min.css' integrity='sha384-X38yfunGUhNzHpBaEBsWLO+A0HDYOQi8ufWDkZ0k9e0eXz/tH3II7uKZ9msv++Ls' crossorigin='anonymous'>\n")
# get current, parent directory
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
# get file list
ls = []
for f in os.listdir(parent_dir):
if os.path.isfile(os.path.join(parent_dir, f)):
ls.append(f)
# add file update time
lss = []
for file in ls:
updated_time = os.path.getmtime(parent_dir + "/" + file)
updated_time_dt = datetime.datetime.fromtimestamp(updated_time)
lss.append([file, updated_time_dt])
# sort desc.
lss= sorted(lss, key=lambda x: x[1], reverse=True)
# print html
print("<h1>file list</h1>")
print("<table class='pure-table pure-table-horizontal'>")
print("<thead>")
print("<tr><td>ファイル名</td><td>更新日時</td></tr>")
print("</thead>")
print("<tbody>")
for file in lss:
print("<tr><td>")
print("<a href='" + "../" + file[0] + "'>" + file[0] + "</a>")
print("</td><td>")
print(file[1])
print("</td></tr>")
print("</tbody>")
print("</table>")