在Python中,文件操作主要来自os模块,主要方法如下:
os.listdir(dirname):列出dirname下的目录和文件
os.getcwd():获得当前工作目录
os.curdir:返回当前目录('.')
os.chdir(dirname):改变工作目录到dirname
os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.normpath(path):规范path字符串形式
os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():分离文件名与扩展名
os.path.join(path,name):连接目录与文件名或目录
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径
利用Syntaxhighlighter和os将代码格式化
import os
filepath = 'C:\\Users\\Administrator\\Desktop\\新建文件夹\\lib' # 要处理的文件
def GetFileList(dir): # 获取路径的所有文件
filelist = os.listdir(dir)
return filelist
def Html_file():
count = 1
for i in GetFileList(filepath):
html_header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"\
"<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\"> " \
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/> " \
"<title>" + i + "</title> " \
"<link href=\"../SyntaxHighlighter.css\" type=\"text/css\" rel=\"stylesheet\"> " \
"<link href=\"../_template.css\" rel=\"stylesheet\"> " \
"<script type=\"text/javascript\" src=\"../shCore.js\"></script> " \
"<script type=\"text/javascript\" src=\"../jquery.js\"></script> " \
"<script type=\"text/javascript\"> " \
"$(document).ready(function () { " \
"$(\".article_content pre\").each(function () { " \
"var $this = $(this); " \
"if ($this.attr(\"class\").indexOf(\"brush:\") != -1) { " \
"var lang = $this.attr(\"class\").split(';')[0].split(':')[1]; " \
"$this.attr('name', 'code');" \
"$this.attr('class', lang);" + "}" \
"});"\
"dp.SyntaxHighlighter.HighlightAll('code'); "\
"});"\
"</script>"\
"<div class=\"article_content\"> "\
"<P><FONT color=\"#0000ff\" size=\"3\" face=\"Courier New\">" \
"<STRONG>" + i + "</FONT></STRONG></P> "\
"<p><textarea cols=\"88\" rows=\"5\" name=\"code\" class=\"Ruby\">"
print(i)
table_file = Compose_html(i, html_header)
filename = 'C:\\Users\\Administrator\\Desktop\\新建文件夹\\kk\\{}.html'.format(i)
print('正在准备生成第{}个文件,请等待!!!'.format(count))
with open(filename, "w+", encoding='utf-8') as f:
f.write(table_file)
print('第{}个文件生成完毕! 请查看!'.format(count))
count = count + 1
def Compose_html(i, html_header): # 合成头和尾
file = 'C:\\Users\\Administrator\\Desktop\\新建文件夹\\lib\\' + i
with open(file, "r", encoding='utf-8') as b:
html_file = html_header + b.read()
return html_file
Html_file()
网友评论