1

I have a list of images in a folder that I want to rename using a text file but keep the extension ".png"

before

folder images
0001.png 
0002.png
0003.png
0004.png
0005.png

namelist.txt
00_02_32_200__00_02_35_158
00_02_36_036__00_02_38_915
00_02_39_331__00_02_43_165
00_02_43_501__00_02_46_220
00_02_50_216__00_02_53_174

after

00_02_32_200__00_02_35_158.png
00_02_36_036__00_02_38_915.png
00_02_39_331__00_02_43_165.png
00_02_43_501__00_02_46_220.png
00_02_50_216__00_02_53_174.png
import os 
def chngname():
    os.chdir('C:/images')
    with open('C:/namelist.txt','r') as jabber:
        content=jabber.read().splitlines()
        director=[x for x in os.listdir()]
        director.sort()
        return content,director



newname = chngname()
os.chdir('C:/images')
for id, file in enumerate(newname[1]):
    os.rename(file, newname[0][id])

This script works fine. The problem is that the extension "png" is not saved I hope to help me. Thanks

  • Does this answer your question? [How rename the images in folder](https://stackoverflow.com/questions/18805348/how-rename-the-images-in-folder) – GooJ May 07 '23 at 21:26
  • I'd also add, I'd recommend using pathlib for anything path related! https://stackoverflow.com/questions/54152653/renaming-file-extension-using-pathlib-python-3 – GooJ May 07 '23 at 21:27

1 Answers1

1

You can use pathlib to rename your files:

import pathlib

IMG_DIR = pathlib.Path('C:/images')

with open('C:/namelist.txt') as jabber:
    content = jabber.read().splitlines()
    director = sorted(IMG_DIR.iterdir())
    for src, dest in zip(director, content):
        src.rename(IMG_DIR / f'{dest}{src.suffix}')

Before:

images/
├── 0001.png
├── 0002.png
├── 0003.png
├── 0004.png
└── 0005.png

After:

images/
├── 00_02_32_200__00_02_35_158.png
├── 00_02_36_036__00_02_38_915.png
├── 00_02_39_331__00_02_43_165.png
├── 00_02_43_501__00_02_46_220.png
└── 00_02_50_216__00_02_53_174.png
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • One minor nitpick: please either use `zip(director, jabber)` to avoid loading file into memory at all (open file is an iterator of its lines), or use `.readlines()` and close content manager immediately after `content` is populated (`.read().splitlines()` is not very clean) to avoid having too much in scope. – STerliakov May 07 '23 at 22:06