0

I have a folder contains images. each image named as

abc_001.jpg 
abc_002.jpg 

I need to rename the images by deleting the first text abc_ and start from the number

I did as

import os

path = '/Desktop/my_folder'

folder = os.fsencode(path)

filenames = []

for file in os.listdir(folder):
    filename = os.fsdecode(file)
    if filename.endswith ('.jpg'):
          filenames=filename.replace('abc_','')

but it doesn't work . how can I replace the first text or deleting them?

i tried

for file in os.listdir(folder):
    filename = os.fsdecode(file)
    if filename.endswith ('.jpg'):
        filenames = filename.replace('abc_', '')
        os.rename(filename, filenames)

but got

 os.rename(filename, filenames)
FileNotFoundError: [Errno 2] No such file or directory: 'abc_000000000009.jpg' -> '000000000009.jpg'
user5520049
  • 101
  • 5

3 Answers3

0

You can use os.rename(source, destination) to rename either file or directory

where source is your file path, and destination is the new file name path

Sin Han Jinn
  • 574
  • 3
  • 18
0

You need to use os.rename(src, dst) instead of filename.replace. Let me know if you have any issues.

You need to rename the file in the following order:

for file in os.listdir(folder):
    filename = os.fsdecode(file)
    if filename.endswith ('.jpg'):
          new_file_name=filename.replace('abc_','')
           os.rename(filename, new_file_name)
Afiz
  • 453
  • 4
  • 13
  • i got FileNotFoundError: [Errno 2] No such file or directory: 'abc_' -> '' – user5520049 Mar 01 '21 at 05:45
  • see my updated solution.. you need to replace `abc_` with your normal string replace method and pass the new file name to `os.rename` – Afiz Mar 01 '21 at 05:51
  • thanks, i will try it but what I the f here and file_names ? `os.rename(f, file_name)` – user5520049 Mar 01 '21 at 05:51
  • did you mean ` filenames = filename.replace('abc_', '') os.rename(filename, filenames)` – user5520049 Mar 01 '21 at 05:53
  • Yes, I have updated the snippet with your code. – Afiz Mar 01 '21 at 05:54
  • thanks for your effort but the folder has several images and got this `os.rename(filename, filenames) FileNotFoundError: [Errno 2] No such file or directory: 'abc_000000000009.jpg' -> '000000000009.jpg'` but I checked again and the image exists – user5520049 Mar 01 '21 at 05:58
0

I solved the problem so anyone who faces the same problem can try it

for file in os.listdir(folder):
    filename = os.fsdecode(file)
    if filename.endswith ('.jpg'): 
        filenames = filename.replace('abc_', '')
        os.rename(os.path.join(path,filename), os.path.join(path,filenames))
user5520049
  • 101
  • 5