久仰python大名,今日猫总刚好有个小需求,要将当前文件夹内的3位文件名逆转过来,例如:
123.txt变成321.txt
ABC.jpeg变成CBA.jpeg
上手python择日不如撞日,动工!
一番google + stackoverflow + python docs之后,程序出炉:
import os for fullname in os.listdir("."): #print fullname #print len(fullname) if fullname.find(".")==3: #print "bingo" print "original: " + fullname #print fullname[::-1] #reverse a string newname = fullname[:fullname.rfind(".")][::-1] + fullname[fullname.rfind("."):] print "new: " + newname os.rename(fullname, newname)
里面有个stackoverflow网友称为比较pythonic的招数:extended slices
fullname[::-1] #reverse a string
其它也就没什么特别了。
程序写完,测试OK,但要别人能在windows下方便使用还是要打包成exe啊,没问题,有py2exe: http://www.py2exe.org
试了一下这里的方法:http://www.py2exe.org/index.cgi/Tutorial
可以是可以,但是发现打包出来的文件很散乱,依赖的文件没有打包到exe中去,不方便!
于是找到了这个帖子:http://stackoverflow.com/questions/112698/py2exe-generate-single-executable-file#113014
minty的回复完美解决了问题。所有依赖文件都打包到了一个exe中。
至此本人首个python程序出炉。一点小感受:
python的确很简洁高效,而且开源的支持很多,适合快速构建应用。Great stuff.
references:
The Python Standard Library http://docs.python.org/2/library/index.html
Rename Files in Python http://stackoverflow.com/questions/2759067/rename-files-in-python
Reverse a string in Python http://stackoverflow.com/questions/931092/reverse-a-string-in-python
Extended Slices http://docs.python.org/release/2.3.5/whatsnew/section-slices.html
py2exe tutorial http://www.py2exe.org/index.cgi/Tutorial
py2exe - generate single executable file http://stackoverflow.com/questions/112698/py2exe-generate-single-executable-file#113014