I'm just trying to write a python script that will change the file name in the file directory

I am trying to create a script in python 2.7 that will rename all files in a directory. Below is the code that I have. The first function removes any numbers in the file name. The second function is to rename the new file name. I get the following error while executing the second function:

[Error 183] Unable to create file if this file already exists

I know that this is because I do not iterate over the files and add the extension number to the new file name, so the script changes the name of the first file and then tries to change the name of the second file to the same name as the first, creating an error.

Can someone help me create a loop that adds an incremental number to every file name in a directory?

I tried adding:

if file_name == filename:
file_name = file_name + 1

in a while loop, but this obviously does not work, because I cannot concatenate an integer with a string.

import os
def replace_num():
    file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
    print(file_list)
    saved_path = os.getcwd()
    print("Current Working Directory is " + saved_path)
    os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
    for file_name in file_list:
        print("Old Name - " + file_name)
        os.rename(file_name, file_name.translate(None, "0123456789"))
    os.chdir(saved_path)
replace_num()

def rename_files():
    file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
    print(file_list)
    saved_path = os.getcwd()
    print("Current Working Directory is " + saved_path)
    os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
    for new_name in file_list:
        print("New Name - " + new_name)
        try:
            os.rename(new_name, "iPhone")
        except Exception, e:
            print e
rename_files()
+4
source share
1 answer

instead of doing:

if file_name == filename:
    file_name = file_name + 1

do something like this:

counter = 0
for file_name in file_container:
    if file_name == file_name: # this will always be True - so it unnecessary
        file_name = "{0}_{1}".format(file_name, counter)
        counter += 1
+4
source

Source: https://habr.com/ru/post/1652553/


All Articles