-1
votes

I am trying to rename images in a folder based on names stored in a .csv.

I realy don't understand what's the issue with below code. The images and .csv are in the same folder

with open('labels.csv', 'r') as f:
    lines = csv.reader(f, delimiter = ',')
    for line in lines:
        os.rename(line[0], line[1] + str('.png'))

I get below error.

FileNotFoundError: [WinError 2] The system cannot find the file specified: '100000.png' -> '1.png'

I tried this in the past (a while ago) and worked. Is the issue in the .csv, the logic or the images?

1
Are you sure that all the cases of line[0] are possible, that is, the line image[0] are in that folder? - eyllanesc
@eyllanesc Yes, '100000.png' is the first image. - Daniel Vargas

1 Answers

1
votes

You should provide absolute path.you can append directory path by variable

 os.path.dirname(__file__)

It will give you current script file path's directory. Subsequently, you need to join directory path and current file name(os.path.join())

You should make CSV files directory as current directory. os.chdir() is function. Please let me know if you need code as help.

import os.path
import csv
current_directory =  os.path.dirname(__file__)
csv_file_path = os.path.join(current_directory,'labels.csv')
with open(csv_file_path, 'r') as f:
    lines = csv.reader(f, delimiter = ',')
    for line in lines:        
        current_file_path = os.path.join(current_directory,line[0])
        renamed_file_path = os.path.join(current_directory,line[1] + ".png")
        os.rename(current_file_path, renamed_file_path)

Please put your .py file in the same directory.