Search code examples
pythonfiledirectory

Rename files within a folder - Python


How can I rename files inside a folder without knowing their original name? For example I have a file.jpg and without knowing what it's called I want to call it test.jpg, this with all the files inside a folder.


Solution

  • Try this:

    import os
    import glob
    # Getting all files in a folder (including hidden files)
    files = os.listdir(os.path.expanduser("~/Downloads"))
    
    # Getting all .jpg files in a directory
    jpeg_files = glob.glob(os.path.expanduser("~/Downloads/*.jpeg"))
    
    print(jpeg_files)
    os.rename(jpeg_files[0], os.path.expanduser("~/Downloads/test.jpeg"))
    

    If you want to rename all of the .jpeg files, then replace the last line with:

    for file in jpeg_files:
        os.rename(file, os.path.expanduser("~/Downloads/test.jpeg"))
    

    Right now I'm using os.expanduser() just so that it's easier for people to test