Mark K
Mark K

Reputation: 9348

Python basic - renaming files

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

I can do it by putting the names into an Excel spreadsheet and rename them 1 by 1. However I want to learn it from a list way.

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 is renamed.

What is the right way to do it from list? And is there the risk that the files are renamed, but not in right order?

Upvotes: 3

Views: 114

Answers (3)

timgeb
timgeb

Reputation: 78690

The problem is the nested loop, look at 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)

Upvotes: 4

Goodnix
Goodnix

Reputation: 43

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)])

Upvotes: 2

rajeshv90
rajeshv90

Reputation: 584

You can use zip

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

Upvotes: 4

Related Questions