1. 程式人生 > >python獲取目錄下所有的檔案並修改檔名(隨機8位字元竄名字)

python獲取目錄下所有的檔案並修改檔名(隨機8位字元竄名字)

class ChangeName(object):

    def getRandom(self):
        seed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        sa = []
        for i in range(8):
            sa.append(random.choice(seed))
        salt = ''.join(sa)
        return salt

    def file_extension(self, path):
        return os.path.splitext(path)[1]

    def getSrcFileName(self, file_dir):
        for root, dirs, files in os.walk(file_dir):
            for file in files:
                # print file
                # 修改所有檔案的名字
                houzhui = self.file_extension(file)
                newname = self.getRandom() + houzhui
                srcpath = root
                newpath = srcpath.replace('src', 'tar')
                print srcpath + file
                print newpath + newname
                if not os.path.exists(newpath):
                    os.mkdir(newpath)
                os.rename(srcpath + "/" + file, newpath + "/" + newname)

    def run(self):
        # 1.獲取元目錄所有的檔名
        path = os.path.abspath(os.path.dirname(__file__))
        self.getSrcFileName(path + "/src")


if __name__ == "__main__":
    obj = ChangeName()
    obj.run()