例如,根据顺序,有5个文件要重命名,1比1。
我可以通过将名称放入Excel电子表格并将其重命名为1来实现。但我希望从列表方式中学习它。
我尝试了以下内容:
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)
它不起作用,只重命名第一个文件。
从列表中执行此操作的正确方法是什么?是否存在重命名文件但风格不正确的风险?
答案 0 :(得分:4)
您可以使用zip
for a,b in zip(l,ll):
os.rename(a, b)
答案 1 :(得分:4)
问题是嵌套循环,看看它的作用:
>>> 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
您的程序可以通过迭代zip(l,ll)
:
for old, new in zip(l,ll):
os.rename(old,new)
答案 2 :(得分:2)
如果你想一对一地重命名,试试这个:
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)])