将当前的目录及其下面的文件依据文件位置生成index.html便于访问
#!/usr/bin/python
#-*- conding=utf-8 -*-
import os
class file:
def __init__(self,item_path,item_name):
self.path=item_path
self.name=item_name
def __str__(self):
n=self.path.count('\\')
return '{}<a href={}>{}</a><br>\n'.format(" "*2*n,self.path.replace(' ','%20'),self.name)
class folder:
def __init__(self,item_path,content=None):
self.path=item_path
if content is None:
self.content=[]
if os.path.isdir(self.path):
self.name=self.path.split('\\')[-1]
content=[]
if self.name:
def key_func(x):
try:
return int(x.split('、')[0])
except (TypeError,ValueError) as err:
return 999
for item in sorted(os.listdir(self.path),key=key_func):
temp_path=os.path.join(self.path,item)
if os.path.isdir(temp_path):
content.append(folder(temp_path,item))
else:
content.append(file(temp_path,item))
self.content=content
def __str__(self):
n=self.path.count('\\')
output='{}<a href={}>【{}】</a><br>\n'.format(" "*2*n,self.path.replace(' ','%20'),self.name)
for item in self.content:
output+="{!s}".format(item)
return output
class display:
def __init__(self,path='.'):
self.path=path
self.HTML_TEMP=('<!DOCTYPE HTML>\n'
'<html>\n<head>\n<meta charset="utf-8">\n<title>文件目录</title>\n</head>\n'
'<body>\n{!s}\n</body>\n'
'</html>')
def make_html(self):
with open('index.html','w',encoding='utf-8') as f:
text=self.HTML_TEMP.format(folder(self.path))
f.write(text)
display().make_html()