我需要帮助以相同的前缀“cat_”重命名文件夹中的 .jpg 文件。例如,070.jpg 应重命名为 cat_070.jpg。
这些文件位于 Cat 文件夹中:
from pathlib import Path
p = Path('C:\\Users\\me\\Jupiter_Notebooks\\Dataset\\Train\\Cat\\')
所以我不太明白该怎么做?下面的内容是错误的,因为它没有“查看”此目录中的文件。
p.rename(Path(p.parent, 'cat_' + p.suffix))
我也尝试过失败:
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\\'
我该怎么办?抱歉,我真的是这里的初学者。
怎么样:
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
还支持重命名文件,因此这里甚至不需要os
模块。
以下是如何使用 rename 和 with_name 函数使用 pathlib 重命名文件:
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\prof_mitts\file_to_unname.txt
path.rename(path.with_name(path.with_name(f"{path.stem.replace('re','un')}{path.suffix}")))
使用路径库。小路。 iterdir() 重命名目录中的所有文件
1) for path in pathlib. Path("a_directory"). iterdir():
2) if path. is_file():
3) old_name = path. stem. original filename.
4) old_extension = path. suffix. original file extension.
5) directory = path. parent. ...
6) new_name = "text" + old_name + old_extension.
7) path. rename(pathlib.