Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python basic - renaming files

Tags:

python

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?

like image 823
Mark K Avatar asked May 16 '26 07:05

Mark K


2 Answers

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)
like image 118
timgeb Avatar answered May 18 '26 20:05

timgeb


You can use zip

for a,b in zip(l,ll):
    os.rename(a, b)
like image 22
rajeshv90 Avatar answered May 18 '26 20:05

rajeshv90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!