Python basic - renaming files

For example, there are 5 files that need to be renamed, from 1 to 1 according to the sequence.

I can do this by putting the names in an Excel spreadsheet and renaming them 1 to 1. However, I want to examine it from the list.

I tried the following:

import os

l = ['c:\\3536 OK-LKF.txt', 'c:\\2532 PK-HHY.txt', 'c:\\1256 OK-ASR.txt', 'c:\\521 OL-MRA.txt', 'c:\\2514 LP-GRW.txt']

ll = ['c:\\aa.txt', 'c:\\bb.txt', 'c:\\cc.txt', 'c:\\dd.txt', 'c:\\ee.txt']

for a in l:
    for b in ll:
        os.rename(a, b)

      

It doesn't work and only the 1st file gets renamed.

What's the correct way to do this from a list? And is there a risk of renaming the files but not in the correct order?

+3


source to share


3 answers


The problem is with the nested loop, see what it does:

>>> l = ['c:\\3536 OK-LKF.txt', 'c:\\2532 PK-HHY.txt', 'c:\\1256 OK-ASR.txt', 'c:\\521 OL-MRA.txt', 'c:\\2514 LP-GRW.txt']
>>> 
>>> ll = ['c:\\aa.txt', 'c:\\bb.txt', 'c:\\cc.txt', 'c:\\dd.txt', 'c:\\ee.txt']
>>> for a in l:
...     for b in ll:
...         print('renaming {} to {}'.format(a,b))
... 
renaming c:\3536 OK-LKF.txt to c:\aa.txt
renaming c:\3536 OK-LKF.txt to c:\bb.txt
renaming c:\3536 OK-LKF.txt to c:\cc.txt
renaming c:\3536 OK-LKF.txt to c:\dd.txt
renaming c:\3536 OK-LKF.txt to c:\ee.txt
renaming c:\2532 PK-HHY.txt to c:\aa.txt
renaming c:\2532 PK-HHY.txt to c:\bb.txt
renaming c:\2532 PK-HHY.txt to c:\cc.txt
renaming c:\2532 PK-HHY.txt to c:\dd.txt
renaming c:\2532 PK-HHY.txt to c:\ee.txt
renaming c:\1256 OK-ASR.txt to c:\aa.txt
renaming c:\1256 OK-ASR.txt to c:\bb.txt
renaming c:\1256 OK-ASR.txt to c:\cc.txt
renaming c:\1256 OK-ASR.txt to c:\dd.txt
renaming c:\1256 OK-ASR.txt to c:\ee.txt
renaming c:\521 OL-MRA.txt to c:\aa.txt
renaming c:\521 OL-MRA.txt to c:\bb.txt
renaming c:\521 OL-MRA.txt to c:\cc.txt
renaming c:\521 OL-MRA.txt to c:\dd.txt
renaming c:\521 OL-MRA.txt to c:\ee.txt
renaming c:\2514 LP-GRW.txt to c:\aa.txt
renaming c:\2514 LP-GRW.txt to c:\bb.txt
renaming c:\2514 LP-GRW.txt to c:\cc.txt
renaming c:\2514 LP-GRW.txt to c:\dd.txt
renaming c:\2514 LP-GRW.txt to c:\ee.txt

      



Your program can be fixed by iterating over zip(l,ll)

:

for old, new in zip(l,ll):
    os.rename(old,new)

      

+4


source


You can use zip



for a,b in zip(l,ll):
    os.rename(a, b)

      

+4


source


If you want to rename one to one try this:

import os

l = ['c:\\3536 OK-LKF.txt', 'c:\\2532 PK-HHY.txt', 'c:\\1256 OK-ASR.txt', 'c:\\521 OL-MRA.txt', 'c:\\2514 LP-GRW.txt']

ll = ['c:\\aa.txt', 'c:\\bb.txt', 'c:\\cc.txt', 'c:\\dd.txt', 'c:\\ee.txt']

for a in l:
    os.rename(a, ll[l.index(a)])

      

+2


source







All Articles