Python: Read a .txt file and change the name of files in directory with .txt index

Question:

I have a directory that contains lots of images and meanwhile, I have a .txt file that contains names like in the below format. I would like to change the name of images based on text file titles. There are 100 names and 100 images in a folder.

Inside Text Files

Flower Blue
Flower Red
Flower Black
Flower orange

Inside Folder

001.mp4
002.mp4
003.mp4
004.mp4

Code Below code does not change the name

import os
import shutil

dirpath = "/media/cvpr/CM_22/inst_you/vidoes"

for file in os.listdir(dirpath):
    with open('/media/cvpr/CM_22/inst_you/vidoes_name') as f:
        lines = [line.rstrip('n') for line in f]
        print(file)
        newfile = os.path.join(dirpath, file.split("_", 1)[1])
        print(newfile)
        os.rename(os.path.join(dirpath, file), newfile)
Asked By: Khawar Islam

||

Answers:

Assuming input.txt contains the new file names and they are the names of corresponding files 001.mp4, 002.mp4, etc., using the pathlib module already provided in Python is more straightforward:

from pathlib import Path

with open('input.txt') as names:
    # Read and number lines starting from 1.
    for i, line in enumerate(names, 1):
        # Generate original filename (001.mp4, 002.mp4, etc.)
        p = Path(f'{i:03d}.mp4')
        # .with_stem() replaces the base name of file
        p.rename(p.with_stem(line.strip()))
Answered By: Mark Tolonen

I think you should put the for inside the with, and use zip to generate one new filename and one old filename each time.
It should be something like:

with open('/media/cvpr/CM_22/inst_you/vidoes_name') as f:  
        lines = [line.rstrip('n') for line in f]
        for old_filename, new_filename in zip(os.listdir(dirpath), lines):
            print(old_filename)
            print(new_filename)
            newfile = os.path.join(dirpath, new_filename.split("_", 1)[1])
            print(newfile)
            os.rename(os.path.join(dirpath, old_filename), newfile)
Answered By: qaqualia
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.