python小试牛刀

python小试牛刀

昨天跑到一个老外的网站,下了好多的歌曲,可是下载下载的文件都是“p=GetFile&item= + 歌曲名”的形式,如此多的歌曲,一个个改名明显不符合本人懒惰的习惯,所以决定让电脑来带班。
首先想到的是用C++(因为本人这段时间在研究),可弄了半天也没搞定,郁闷,改用Java的话,又没多大提高。于是决定用python。这玩艺还真方便,短短数行代码就搞定了。
 
附上代码
import os
STARTFIX = "p=GetFile&item="
DIR_PATH = "C:\oscar\unknowns\"
dirs = os.listdir(DIR_PATH)
def shoudChange(name):
    if name.find(STARTFIX) == -1:
        return 0
    else:
        return 1
def changeName(name):
    rtn = name.replace(STARTFIX, "")
    rtn = rtn.replace("+", " ")
    rtn = rtn.replace("-", " ")
    return rtn   
for dir in dirs:
    if not os.path.isdir(dir):
        if shoudChange(dir) == 1:
            oldname = DIR_PATH + dir
            newname = DIR_PATH + changeName(dir)
            print oldname
            print newname
            try:
                os.rename(oldname, newname)
            except:
                print ‘there is an error when rename’

One thought on “python小试牛刀

Leave a Reply

Your email address will not be published. Required fields are marked *