Skip to content

Instantly share code, notes, and snippets.

@gologius
Created April 19, 2019 02:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gologius/2613f3c3c90b6470cda532a1097f033f to your computer and use it in GitHub Desktop.
Save gologius/2613f3c3c90b6470cda532a1097f033f to your computer and use it in GitHub Desktop.
ディレクトリ構成を、HTML表に転記するスクリプトです。細かいことは全く考慮してません。
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 17 22:47:22 2019
@author: gologius
"""
import os
PATH=r"sample"
DOMAIN="http://localhost"
HEADER = '''\
<head>
<style>
table {
border:solid #000000 1px;
border-collapse: collapse
}
table th,td{
border:solid #000000 1px;
padding :5px;
}
ul, ol {
padding-left:15px;
}
</style>
</head>
'''
def get_max_depth(path, depth):
result = depth
#ディレクトリのみ
for f in os.listdir(path):
fullpath = path + "\\" + f
if os.path.isdir(fullpath):
tmp = get_max_depth(fullpath, depth+1) #次の階層へ
if tmp > result:
result = tmp
return result
def dig(abspath, relpath, depth, dirno, max_depth):
#depthに応じてダミーセル追加
for i in range(depth*2):
char = ""
if i == (depth-1)*2:
char = ""
elif i > (depth-1)*2:
char = ""
print('<td>{0}</td>'.format(char))
#タイトル
title = relpath.split('\\')[-1]
print('<td><p>' + title + '</p></td>')
#ファイルのみ
print('<td>')
print('<ul>')
for f in os.listdir(abspath):
fullpath = abspath + "\\" + f
if os.path.isdir(fullpath) == False:
try:
url = DOMAIN + relpath+'/'+f
url = url.replace('\\', '/')
print('<li><a href="{0}">{1}</a></li>'.format(url, f))
except UnicodeEncodeError:
print('<li><a href="dummy">ファイル名変換エラー</a></li>')
print('</ul>')
print('</td>')
#depthに応じてダミーセル追加
for i in range((max_depth-depth)*2):
print('<td></td>')
#ディレクトリのみ
for i,f in enumerate(os.listdir(abspath)):
fullpath = abspath + "\\" + f
if os.path.isdir(fullpath):
print('<tr>')
dig(fullpath, relpath+'\\'+f, depth+1, i, max_depth) #次の階層へ
print('</tr>')
return
def main():
max_depth = get_max_depth(PATH, 0)
print('<!DOCTYPE html><html>')
print(HEADER)
print('<body>')
print('<table>')
dig(PATH, PATH.split('\\')[-1], 0, 0, max_depth)
print('</table>')
print('</body>')
print('</html>')
return
main()
@gologius
Copy link
Author

gologius commented Apr 19, 2019

こんな感じに出力されます
dir2html_sample

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment