python os.rename(…) won't work !

前端 未结 6 801
离开以前
离开以前 2020-12-22 00:26

I am writing a Python function to change the extension of a list of files into another extension, like txt into rar, that\'s just an idle example. But I\'m getting an error

6条回答
  •  北海茫月
    2020-12-22 01:05

    import os
    
    def extChange(path,newExt,oldExt=""):
        if path.endswith != "\\" and path.endswith != "/":
            myPath = path + "\\"
        directory = os.listdir(myPath)
        for i in directory:
            x = myPath + i[:-4] + "." + newExt
            y = myPath + i
            if oldExt == "":
                os.rename(y,x)
            else:
                if i[-4:] == "." + oldExt:
                    os.rename(y,x)
    

    now call it:

    extChange("C:/testfolder/","txt","lua") #this will change all .txt files in C:/testfolder to .lua files
    extChange("C:/testfolder/","txt") #leaving the last parameter out will change all files in C:/testfolder to .txt
    

提交回复
热议问题