У меня есть папка в D:/
, которая имеет следующую структуру:
folder
\ tic\file0.jpg
\ tic\file1.jpg
\ tic\ tik\ file2.png
.
.
.
\ tik\xxx.png
\ tik\yyy.jpg
\ tik\zzz.png
.
.
.
Я хочу найти все подпапки с именем tik
из D:/folder
и переименовать в tok
. Как я могу сделать это на Python?
Ожидаемый результат:
folder
\ tic\file0.jpg
\ tic\file1.jpg
\ tic\ tok\ file2.png
.
.
.
\ tok\xxx.png
\ tok\yyy.jpg
\ tok\zzz.png
.
.
.
Пока я пробовал следующий код, но он не работает:
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))
Обновление:
Я создаю фальшивую структуру папок с именем file
следующим образом:
Я хочу переименовать tic
в toc
с кодом ниже:
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)
но я получаю ошибку:
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'