仕事で仕様書に書くために、ファイルをリストアップするプログラムをちゃちゃっと書いたが、ちょっと機能不足だったので、家で書いてみた。
jsonモジュール使ってみたい!とか、家で使う際の機能を入れてみたりとか、欲望にまみれて書いたので、コードとは完全に別物になっちゃったけど。
コード
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 指定された拡張子のみ、HTML形式(Table/List)で出力する
# fileNameDictに定義されているものは、置換する
from __future__ import print_function
import sys,os
import codecs
import json
from string import Template
from optparse import OptionParser
#リストアップ対象拡張子
ext_dic = [u'jpg']
#ファイル対比表のファイル名
dictFileName= u'filelistup_dict.json'
def isTarget(ext):
return True if ext.lower() in ext_dic else False
def load_json(fname, encoding = 'utf-8'):
with open(fname) as f:
return json.load(f, encoding)
def writeHTML(sourcePath,table,outputHTMLTemplate):
o=codecs.open( os.path.join(os.path.dirname(unicode(sys.argv[0],"mbcs")),outputFileName) ,'w','utf-8')
o.write(outputHTMLTemplate.substitute({'dir': sourcePath.replace('\\', '/').split('/')[-1], 'files': table}))
o.close()
def listupTable(sourcePath,fileNameDict,options):
tableDirectoryTemplate = Template(u'\n\n${dir}\n | \n
\n')
table=''
uniqid=1
for root, dirs, files in os.walk(sourcePath):
(rootPath,fileName) = os.path.split(root)
if options.isRelPath == True:
table += tableDirectoryTemplate.substitute({'dir': os.path.relpath(root,os.path.split(sourcePath)[0])})
else:
table += tableDirectoryTemplate.substitute({'dir': root.replace(rootPath + u'\\',u'')})
for file in files:
if isTarget(file.split(".")[-1]) == True:
line = u'{0} | {1} | - |
\n'.format(uniqid,fileNameDict.get(file,file))
table += line
uniqid+=1
return table
def listupList(sourcePath,fileNameDict,options):
listDirectoryTemplate = Template(u'
${dir}\n')
list=''
for root, dirs, files in os.walk(sourcePath):
(rootPath,fileName) = os.path.split(root)
if options.isRelPath == True:
list += listDirectoryTemplate.substitute({'dir': os.path.relpath(root,os.path.split(sourcePath)[0])})
else:
list += listDirectoryTemplate.substitute({'dir': root.replace(rootPath + u'\\',u'')})
list += u''
for file in files:
if isTarget(file.split(".")[-1]) == True:
list += u'- '+ fileNameDict.get(file,file) + u''
list += u'
\n\n'
return list
def listupFile(sourcePath,dictPath,options):
if os.path.isfile(dictPath):
fileNameDict = load_json(dictPath,'utf-8')
else:
fileNameDict = {}
outputHTMLTemplate = Template(u'aaa')
if options.isList == True:
outputHTMLTemplate = Template(u'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n\n\n\n\n\n\n\n\n')
contents = listupList(sourcePath,fileNameDict,options)
else:
outputHTMLTemplate = Template(u'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n\n\n\n\n\n\n\n\n')
contents = listupTable(sourcePath,fileNameDict,options)
writeHTML(sourcePath,contents,outputHTMLTemplate)
if __name__=='__main__':
parser = OptionParser(version="0.5")
parser.add_option("-o",
action="store",type="string",dest="filename",default=u'filelist.html',
help=u"The output file name is specified.",metavar="FILENAME")
parser.add_option("-l","--List",
action="store_true",dest="isList",default=False,
help=u"The output file type is List Format.")
parser.add_option("-r","--Enable relative filepath",
action="store_true",dest="isRelPath",default=False,
help=u"output rrelative path.")
(options, args) = parser.parse_args()
outputFileName = options.filename
#引数がおかしい場合
if len(sys.argv) < 2:
print(u'Usage: # python',sys.argv[0],u'[sourcedirectorypath] -r -l -o "outputFile.html"')
quit()
dictPath = os.path.join(os.path.split(sys.argv[0])[0],dictFileName)
sourcePath = os.path.dirname(unicode(sys.argv[1],"mbcs") + '\\')
if os.path.isdir(sourcePath) == False: #存在しないPathを指定した場合
print(u'The directory does not exist.',sourcePath)
quit()
else:
listupFile(sourcePath,dictPath,options)
filelistup_dict.json
pythonと同じ階層にファイル置いておくと、ファイル名を置き換えてくれる。
まぁ、普段使うことは無いと思うけど。
{
"test1.jpg":"ああああ",
"test2.jpg":"いいいい"
}
続きを読む
posted by MINE at 01:06
|
Comment(0)
|
TrackBack(0)
|
Python
|

|

|
edit