Renaming multiple files at once with Python
Question: I am new to programming. I usually learn for a while , then take a long break
and forget most of what I learned. Nevermind that back info.

I tried to create a function which would help me rename files inside a folder
and then add an increment at the end of the new name (e.g. blueberry1,
blueberry 2,...)

    
    
    import os
    def rename_files(loc,new_name):
        file_list= os.listdir(loc)
        for file_name in file_list:
            count=1
            if count <= len(file_list):
                composite_name = new_name+str(count)
                os.rename(file_name, composite_name)
                count+= 1
    

Well apparently this code doesn't work. Any idea how to fix it?


Answer: You need to join the file to the path:

    
    
     os.rename(os.path.join(loc, file_name), composite_name)
    

You can also use enumerate for the count:

    
    
    import os
    def rename_files(loc,new_name):
        file_list= os.listdir(loc)
        for ind, file_name in enumerate(file_list,1):
                composite_name = new_name+str(ind)
                os.rename(os.path.join(loc, file_name), os.path.join(loc, composite_name)
    

`listdir` just returns the file names, not the path so python would have no
way of knowing where the original file actually came from unless your cwd was
the same directory.

