-1
import os

path = os.chdir("D:\\Photos\\Summer")

i = 0
for file in os.listdir(path):

    new_file_name = "pic{}.jpg".format(i)
    os.rename(file, new_file_name)

    i = i +1

This script rename random named files into pic0 pic1 pic2... But, how to modify this to rename random named files into files from specific range (specific number to specific number)?

For example I have already in my directory files from pic1 to pic100 and I get some new random named, then I want rename them from 101-200.

How to do this?

  • Are you asking how to get a random integer in a range? You seem to know How to rename a file given a number. – mkrieger1 Apr 07 '21 at 18:35
  • You can use `random.randint(101,200)` to get a random number, but remember that you need to be able to handle duplicates. – Tim Roberts Apr 07 '21 at 18:38
  • Note a huge *potential* gotcha: if `new_file_name` already exists as a file (not as a directory) when you call `os.rename(file, new_file_name)` that file will be silently erased and replaced with `file`. With batch renaming, you usually want to test for this before you blindly rename... – dawg Apr 07 '21 at 18:53

1 Answers1

1

Change your initial code to this to start the next set, beginning at 101:

import os

path = os.chdir("D:\\Photos\\Summer")

i = 101
for file in os.listdir(path):

    new_file_name = "pic{}.jpg".format(i)
    os.rename(file, new_file_name)

    i = i + 1

As you can see, changing the variable i to 101 to begin with will start the naming at "pic101".

To move files:

Begin by creating a directory inside "Pictures" called "SummerAutonamed". Then, in the python file:

for file in os.listdir(path):
    filename = file
    os.rename(f"D:\\Photos\\Summer\\{filename}", f"D:\\Photos\\Summer_Autonamed\\{filename}")

Put this code after the code that renames all the files. Then, every file will be renamed and then moved to the folder "Summer_Autonamed". It is imperative that the directory "Summer_Autonamed" exists before you run the program.

The completed code should read:

import os

path = os.chdir("D:\\Photos\\Summer")

i = 101
for file in os.listdir(path):

    new_file_name = "pic{}.jpg".format(i)
    os.rename(file, new_file_name)

    i = i + 1


for file in os.listdir(path):
    filename = file
    os.rename(f"D:\\Photos\\Summer\\{filename}", f"D:\\Photos\\Summer_Autonamed\\{filename}")
Peter Nielsen
  • 251
  • 4
  • 17