Reputation: 10011
I have a folder in D:/
have the following structure:
folder
\ tic\file0.jpg
\ tic\file1.jpg
\ tic\ tik\ file2.png
.
.
.
\ tik\xxx.png
\ tik\yyy.jpg
\ tik\zzz.png
.
.
.
I want to find all subfolders whose name is tik
from D:/folder
and rename it to tok
. How can I do it in Python?
Expected result:
folder
\ tic\file0.jpg
\ tic\file1.jpg
\ tic\ tok\ file2.png
.
.
.
\ tok\xxx.png
\ tok\yyy.jpg
\ tok\zzz.png
.
.
.
So far, I have tried following code but it doesn't work:
import os
import os.path
dir = os.getcwd()
old = "tik"
new = "tok"
for parent, dirnames, filenames in os.walk(dir):
for filename in filenames:
if filename.find(old)!=-1:
newName = filename.replace(old, new)
print(filename, "---->", newName)
os.rename(os.path.join(parent, filename), os.path.join(parent, newName))
Update:
I create a fake folder struction named file
as follows:
I want to rename tic
to toc
with code below:
import os
from pathlib import Path
path = r"C:\Users\User\Desktop\file" # Path to directory that will be searched
old = "tic"
new = "toc"
for root, dirs, files in os.walk(path, topdown=False): # os.walk will return all files and folders in your directory
for name in dirs: # we are only concerned with dirs since you only want to change subfolders
directoryPath = os.path.join(root, name) # create a path to subfolder
if old in directoryPath: # if the word tik is found in your path then
parentDirectory = Path(directoryPath).parent # save the parent directory path
os.chdir(parentDirectory) # set parent to working directory
os.rename(old, new)
but I get error:
Traceback (most recent call last):
File "<ipython-input-10-2c40676a9ed9>", line 13, in <module>
os.rename(old, new)
FileNotFoundError: [WinError 2] System can not find file. : 'tic' -> 'toc'
Upvotes: 2
Views: 163
Reputation: 802
This seems to work well and handles all sub-directories inside your main directory. You will want to add some error handling in case the directory already has a folder named what you intend on changing it to, but this should get you going.
import os
from pathlib import Path
path = r"Enter_path_to_directory_you_want_to_search" # Path to directory that will be searched
old = "tik"
new = "tok"
for root, dirs, files in os.walk(path, topdown=False): # os.walk will return all files and folders in your directory
for name in dirs: # we are only concerned with dirs since you only want to change subfolders
directoryPath = os.path.join(root, name) # create a path to subfolder
if old in directoryPath: # if the word tik is found in your path then
parentDirectory = Path(directoryPath).parent # save the parent directory path
os.chdir(parentDirectory) # set parent to working directory
os.rename(old, new) # change child folder from tik to tok
Upvotes: 1