简体   繁体   中英

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

You should use

for i, j in zip(oldNames, newNames):
    os.rename(i, j)

instead of a nested for-loop.

The zip function iterates the two arrays in lock-step like

os.rename(oldNames[0], newNames[0])
os.rename(oldNames[1], newNames[1])
os.rename(oldNames[2], newNames[2])
....

While the nested-loop will actually perform

os.rename(oldNames[0], newNames[0])
os.rename(oldNames[0], newNames[1])
os.rename(oldNames[0], newNames[2])
os.rename(oldNames[0], newNames[3])
....
os.rename(oldNames[1], newNames[0])
os.rename(oldNames[1], newNames[1])
os.rename(oldNames[1], newNames[2])
os.rename(oldNames[1], newNames[3])
....
os.rename(oldNames[2], newNames[0])
os.rename(oldNames[2], newNames[1])
os.rename(oldNames[2], newNames[2])
os.rename(oldNames[2], newNames[3])
........
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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM