2

I'm trying to batch rename some photos and I wanna the second part only, e.g. renaming from 1234 - Photo_Name.jpg to Photo_Name.jpg.

This is my code:

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)

But I get this Error

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'
  • What is the output of `os.getcwd()` (In other words, is the directory whose files you're trying to modify and the directory of the Python script the same?) – BrokenBenchmark Jan 20 '22 at 06:01
  • You need to add the directory prefix to the names. – Barmar Jan 20 '22 at 06:01
  • In your own words, where the code says `os.rename(file_name, new_filename)`, how do you expect it to decide where to look for `file_name`? You found that name by looking up the contents of the `r"C:\Users\yousef\Downloads\Pictures\\"` folder with `os.listdir`, but why should `os.rename` also know to look there? – Karl Knechtel Jan 20 '22 at 06:25

2 Answers2

1

Try prepending the full path of the folder to the source and destination file variables:

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}")
Allan Chua
  • 9,305
  • 9
  • 41
  • 61
1

It's trying to rename the file in the current directory, not the folder you listed. Use os.path.join() to combine a directory with a filename.

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))
Barmar
  • 741,623
  • 53
  • 500
  • 612