Hello Python! - 記本人首個Python小程序

久仰python大名,今日貓總恰好有個小需求,要將當前文件夾內的3位文件名逆轉過來,例如:html

123.txt變成321.txtpython

ABC.jpeg變成CBA.jpegwindows

上手python擇日不如撞日,動工!測試

一番google + stackoverflow + python docs以後,程序出爐:google

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 slicesspa

fullname[::-1] #reverse a stringcode

其它也就沒什麼特別了。htm

程序寫完,測試OK,但要別人能在windows下方便使用仍是要打包成exe啊,沒問題,有py2exe: http://www.py2exe.orgblog

試了一下這裏的方法:http://www.py2exe.org/index.cgi/Tutorialget

能夠是能夠,可是發現打包出來的文件很散亂,依賴的文件沒有打包到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

相關文章
相關標籤/搜索