alexuuu
alexuuu

Reputation: 53

How to rename all files names in folder based on another file name folder?

I have 1000+ files in 2 folders. I want to rename all of them in 1st folder based on second folder file names?

my test script

import os

for file in os.listdir("/home/folder1"):
    os.rename(file, f"/home/folder2")

Upvotes: 0

Views: 252

Answers (2)

Navaneeth Reddy
Navaneeth Reddy

Reputation: 339

I suggest using os.walk() instead of os.listdir().

os.walk() returns a generator object containing all subfolders, files and parent directories. So just specify the root folder and you are good.

import os

result = list(os.walk())

for parent, directories, files in result:
    if parent == "folder_name_1":
        for file in files:
            os.rename(parent + '/' + file, parent + '/' + "new_name_of_the_file")

This is a vague answer, you might want your renaming logic to be different based on your needs.

Upvotes: 0

Olvin Roght
Olvin Roght

Reputation: 7812

You can use pathlib:

from pathlib import Path

src = Path(r"/home/folder1")
dst = Path(r"/home/folder2")
for s, d in zip(src.iterdir(), dst.iterdir()):
    d.rename(d.with_stem(s.stem))
    # for python lower than 3.9 use next line
    # d.rename(d.with_name(s.with_suffix(d.suffix).name))

P.S. Path.with_stem() have been added in python 3.9, so I've added line with implementation for lower versions.

Upvotes: 3

Related Questions