2

我正在尝试批量重命名一些照片,我只想要第二部分,例如重命名 from 1234 - Photo_Name.jpg to Photo_Name.jpg

这是我的代码:

import os

folder = r"C:\Users\yousef\Downloads\Pictures\\"
files = os.listdir(folder)
for file_name in files:
    new_filename = file_name.split(' - ')[1]
    os.rename(file_name, new_filename)

但我得到这个错误

File "c:\Users\yousef\Downloads\code.py", line 7, in <module>
    os.rename(file_name, new_filename)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '1234 - Photo_Name.jpg' -> 'Photo_Name.jpg'
4

2 回答 2

1

尝试将文件夹的完整路径添加到源文件和目标文件变量中:

import os

folder = r"C:\Users\yousef\Downloads\Pictures\\"
files = os.listdir(folder)
for file_name in files:
    new_filename = file_name.split(' - ')[1]
    os.rename(f"{folder}{file_name}", f"{folder}{new_filename}")
于 2022-01-20T06:03:31.620 回答
1

它试图重命名当前目录中的文件,而不是您列出的文件夹。用于os.path.join()将目录与文件名组合在一起。

import os

folder = r"C:\Users\yousef\Downloads\Pictures\\"
files = os.listdir(folder)
for file_name in files:
    new_filename = file_name.split(' - ')[1]
    os.rename(os.path.join(folder, file_name), os.path.join(folder, new_filename))
于 2022-01-20T06:04:35.657 回答