Search code examples
pythonpython-3.xwindowsfile-rename

How to rename multiple files in this case .jpg?


I'm trying to change the file names of a few ".jpg" to a custom name followed by a number. So it would look something like this: Name1.jpg; Name2.jpg; Name3.jpg

Problem that it doesn't change the current name to the new name. the dir is correct.

Image: https://i.sstatic.net/QuAnI.jpg

Source of the tutorial: https://www.geeksforgeeks.org/rename-multiple-files-using-python/

I'm using Python3 on Windows 10 64 Bit

I tried the dir in four different ways.

1. os.listdir('C:/Users/Inty/Desktop/test'):
2. os.listdir('C://Users//Inty//Desktop//test'):
3. os.listdir('C:\Users\Inty\Desktop\\test'):
4. os.listdir('C:\\Users\\Inty\\Desktop\\test'):
5. os.listdir('C:/Users/Inty/Desktop/test/'):

Also played with the dst = '.jpg' to '.JPG' but it doesn't seem to make any difference.

# Imports
import os


# Functions
def main():
    i = 0

    for filename in os.listdir('C:/Users/Inty/Desktop/test'):
        dst = 'Name' + str(i) + '.JPG'
        src = 'C:/Users/Inty/Desktop/test' + filename
        dst = 'C:/Users/Inty/Desktop/test' + dst

        os.rename(src, dst)
        i += 1

    if __name__ == '__main__':
        main()


Process finished with exit code 0

Solution

  • Solved

    I modified the code a bit. The main reason was because I had if __name__ == '__main__': Inside the for loop.

    That made the if inside the function.

    import os
    
    # Functions
    
    PATH = 'C:\\Users\\Inty\\Desktop\\test'
    
    
    def main():
        i = 0
    
        for filename in os.listdir(PATH):
            dst = 'Name' + str(i) + '.JPG'
            src = os.path.join(PATH, filename)
            dst = os.path.join(PATH, dst)
    
            os.rename(src, dst)
            i += 1
    
    if __name__ == '__main__':
        main()