Jose Jose - 7 months ago 14
Python Question

Rename files from several folders. OSError: [Errno 2] No such file or directory

The directory Dates16 contains several folders like a show you below in the first list and each folder has a lot of .txt files. I would like to rename those files like I show you in second list

>>> oldNames
['./Documents/Dates16/Forest/file0.txt'
'./Documents/Dates16/Forest/file1.txt'
'./Documents/Dates16/Forest/file2.txt'
'./Documents/Dates16/Wet/file0.txt'
'./Documents/Dates16/Wet/file1.txt'
'./Documents/Dates16/Winter/file0.txt'
'./Documents/Dates16/Winter/file1.txt'
'./Documents/Dates16/Winter/file2.txt']

>>> newNames
['./Documents/Dates16/Forest/RT-file0.txt'
'./Documents/Dates16/Forest/RM-file1.txt'
'./Documents/Dates16/Forest/RA-file2.txt'
'./Documents/Dates16/Wet/RA-file0.txt'
'./Documents/Dates16/Wet/RT-file1.txt'
'./Documents/Dates16/Winter/RS-file0.txt'
'./Documents/Dates16/Winter/RT-file1.txt'
'./Documents/Dates16/Winter/RT-file2.txt']


Both list have the same length and for rename the files I'm using this code but returns an OSError, this code renames the first element of the lists but then breaks the loop and retuns the output error. So how can I fix this? Thanks

import os
for i in oldNames:
for j in newNames:
os.rename(i,j)
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
OSError: [Errno 2] No such file or directory


This is not a duplicate from Python OSError: [Errno 2] No such file or directory I explained what I'm looking for, and also what does my code do. The other post I really don't understand it and only asked for fix the error

Answer
for i in oldNames:
    for j in newNames:

This is the problem. You're changing the filename of each oldName J times, even though after the first time the file doesn't exist anymore (because it's been renamed).