Reputation: 1291
I need help renaming .jpg files in my folder to add the same prefix, 'cat_'. For example, "070.jpg" should be renamed to "cat_070.jpg".
The files are located within the Cat folder:
from pathlib import Path
p = Path('C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\')
I don't quite see how to do it. The code below is wrong because it does not 'look into' the files in this directory:
p.rename(Path(p.parent, 'cat_' + p.suffix))
I have also unsuccessfully tried this:
import os
from os import rename
from os import listdir
# Get path
cwd = "C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat"
# Get all files in dir
onlyfiles = [f for f in listdir(cwd) if isfile(join(cwd, f))]
for file in onlyfiles:
# Get the current format
if file[-4:]==(".jpg"):
s = file[1]
# Change format and get new filename
s[1] = 'cat'
s = '_'.join(s)
# Rename file
os.rename(file, s)
print(f"Renamed {file} to {s}")
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\'
How can I do it?
Upvotes: 3
Views: 5184
Reputation: 5
use pathlib.Path.iterdir()
to rename all files in a directory
for path in pathlib.Path("a_directory").iterdir():
if path.is_file():
old_name = path. stem. original filename.
old_extension = path. suffix. original file extension.
directory = path.parent. ...
new_name = "text" + old_name + old_extension.
path.rename(pathlib.
Upvotes: -3
Reputation: 1060
Here's how you can rename a file with pathlib using the rename and with_name functions:
import pathlib,datetime
path = pathlib.Path('./file_to_rename.txt').absolute()
print(path.with_name(f"{path.stem.replace('re','un')}{path.suffix}"))
# C:\Users\User\Desktop\folder\file_to_unname.txt
path.rename(path.with_name(path.with_name(f"{path.stem.replace('re','un')}{path.suffix}")))
Upvotes: 1
Reputation: 1050
How about:
from pathlib import Path
img_dir = Path('C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\') # path to folder with images
for img_path in img_dir.glob('*.jpg'): # iterate over all .jpg images in img_dir
new_name = f'cat_{img_path.stem}{img_path.suffix}' # or directly: f'cat_{img_path.name}'
img_path.rename(img_dir / new_name)
print(f'Renamed `{img_path.name}` to `{new_name}`')
pathlib
also supports renaming files, so the os
module is not even needed here.
Upvotes: 5