-3

I have files like: 00001.jpg 00002.jpg . . . 01907.jpg

I want to add some files to this directory which are named the same. But their names should continue like 01908.jpg 01909.jpg . . 12906.jpg

I couldn't manage to do that. How can i make this happen?

Thanks a lot:)

I tried

import os 
files=[]

files = sorted(os.listdir('directory'))
b=len(files)
for i in range(0,b):
    a=files[i]

    os.rename(a,(a+1))

print (files)

2 Answers2

0

you have a source dir (which contains the badly/identical named files) and a target dir (which contains files that should not be overwritten).

I would:

  • list the target dir & sort like you did (the rest of your attempt is clearly off...)
  • get the last item and parse as integer (without extension): add 1 and that gives the next free index.
  • loop in the source dir
  • generate a new name for the current file using the new computed index
  • use shutil.move or shutil.copy to move/copy the new files with the new name

like this:

import os,shutil

s = "source_directory"
d = "target_directory"
files = sorted(os.listdir(d))

highest_index = int(os.path.splitext(files[-1])[0])+1

for i,f in enumerate(sorted(os.listdir(s)),highest_index):
    new_name = "{:05}.png".format(i)
    shutil.copy(os.path.join(s,f),os.path.join(d,new_name))
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

You can do this:

import os
directory1 = 'path to the directory you want to move the files to'
directory2 = 'path to the directory you want to move the files to'

for file in ordered(os.listdir(directory2)):
    counter = len(os.listdir(directory1))
    file_number = int(file.split('.')[0]) #Get the file number
    os.rename(os.path.join(directory2, file), os.path.join(directory1 + str(file_number + counter)))

What I have done:

  • Looped over the files that I wanted to rename and move.
  • Found the number of files, which I assumed that it is going to be the same as the name of the last file in this directory, in the main directory which the files are going to be moved to and made sure it will keep updating itself so that no overwrites happen.
  • Then I got the number of the current file in the loop.
  • Finally, I used os.rename to rename and move the file from the 1st directory to the 2nd.
O.Suleiman
  • 898
  • 1
  • 6
  • 11