0

I need to rename the whole images I have in a folder

img1.jpg to be 1.jpg

i tried like that

import os

s = open('images', 'w')
DIRECTORY = '/img/11/'

for img_filename in os.listdir(DIRECTORY):
    x = os.path.splitext(img_filename)[0].split('jpeg')
    x = img_filename.replace('img_', '')
    s.write(str(x) + '\n')

but need the changes on the files itself

Lei
  • 73
  • 6
  • 2
    `s.write(str(x)+'\n')` tells Python to write `str(x)+'\n'` to the file. You want [`os.rename`](https://docs.python.org/3/library/os.html#os.rename). – 0x5453 Sep 03 '21 at 17:22

2 Answers2

0

Try this:

import os
import pathlib
from pathlib import Path

folder="C:\\Myfile\\path"

for img_filename in os.listdir(folder):
    os.rename(folder/img_filename, folder/ img_filename.replace('COCO_val2014_', ''))
j__carlson
  • 1,346
  • 3
  • 12
  • 20
0

you just had to use the os.rename() function

for img_filename in os.listdir(DIRECTORY):
    print(img_filename)
    x = img_filename.replace('COCO_val2014_','')
    print(x)
    os.rename(DIRECTORY+"\\"+img_filename,DIRECTORY+"\\"+x)
Dr who
  • 7
  • 2