如何使用Python的pathlib模块重命名文件夹中的文件?

问题描述 投票:0回答:3

我需要帮助重命名文件夹中的 .jpg 文件以添加相同的前缀“cat_”。例如,“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\\'

我该怎么做?

python python-3.x file-rename pathlib
3个回答
4
投票

怎么样:

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
模块。


1
投票

以下是如何使用 renamewith_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}")))

-2
投票

使用路径库。小路。 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.
© www.soinside.com 2019 - 2024. All rights reserved.