python编写脚本工具

前言

最近在研究cocos2d-x中的热更新机制,有一个需求是遍历一个文件夹下的所有文件,并计算文件的md5值和大小,最后将文件的目录,md5值和size保存到一个lua文件中。也就是生成如下格式的一个lua文件

1
2
3
4
5
6
7
8
9
10
11
12
local flist = {
appVersion = 1,
version = "1.0.1",
dirPaths = {
{name = "common"},
{name = "common\sound"},
{name = "lib"},
},
fileInfoList={
{name = "a.txt",md5 = "d41d8cd98f00b204e9800998ecf8427e",size = 0},
}

正好之前学了下python,可以拿这个来练练手。直接上代码吧,其实也挺简单的没啥好说的

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#coding:utf-8
import os
import os.path
import hashlib
import sys
#计算文件的md5值
def calfilemd5(file):
md5 = hashlib.md5()
fs = open(file, 'rb')
while True:#--小文件就没必要这样分段计算了
buf = fs.read(1024)
if buf:
md5.update(buf)
else:
break
return md5.hexdigest()
#计算文件的size
def calfilesize(file):
return os.path.getsize(file)
#遍历文件夹并生成flist文件
def genflist(root_dir):
flist = "local flist = {\n" +\
" appVersion = 1,\n" +\
" version = \"1.0.1\",\n" +\
" dirPaths = {\n"
#提取所有目录的路径
for dirpath , dirnames, filenames in os.walk(root_dir):
if root_dir != dirpath:
flist = flist + " {name = \"" + dirpath.replace((root_dir + '\\'),'') + "\"},\n"
flist = flist + "\n },\n fileInfoList={\n"
#计算所有文件的size和md5
for dirpath , dirnames, filenames in os.walk(root_dir):
f_dir = dirpath.replace((root_dir + '\\'),'')
for f in filenames:
f_md5 = calfilemd5(os.path.join(dirpath,f))
f_size = calfilesize(os.path.join(dirpath,f))
last_dir = ''
if root_dir != f_dir:
last_dir = f_dir + '\\' + f
else:
last_dir = f
flist = flist + " {name = \"" + last_dir + "\",md5 = \"" + str(f_md5) + "\",size = " + str(f_size) + "},\n"
flist = flist + " },\n}"
filehandle = open('flist.lua','w')
filehandle.write(flist)
filehandle.close()
if __name__ == '__main__' :
root_dir = sys.argv[1]
genflist(root_dir)

结语

最后不得不说python的语法真严格,缩进不对就直接语法错误了,估计没有第二种语言是这样设计的了。