Change the file name by using python

Question:

I would like to change the file name in the folder, there are jpg file but corrupted with product id number. I tried to rename it and delete the string after ".jpg" by using python, here is the code, but there is no any change.

Do you guys have any suggestion?

import os

path=input('C:\Users\pengoul\Downloads\Files\PIC\')    

def rename(path):

    for file in os.listdir(path):

        if file.endswith(".jpg@v=*"):
            print(file)

            newfile=file.split("@",1)[0]
        
            newName=file.replace(file,newfile)
                    
            os.rename(os.path.join(path,file),os.path.join(path,newName))
 
rename(path)

print("End")

Rename the file of one folder and delete the string after .jpg by using python.

Asked By: pengoul

||

Answers:

if you input path from user, python automatically use "" instead of "\" so you shouldn’t use "\" while input. So I suggest one of these two ways:

path = input("Input your Path: ")
# And the user entered this: 'C:UserspengoulDownloadsFilesPIC'

or

path = 'C:\Users\pengoul\Downloads\Files\PIC'

or

path = r'C:UserspengoulDownloadsFilesPIC'

I hope that works for you. If not, make us aware of that!

Answered By: Pedram Porbaha