比如有5个文件要重命名,按顺序1比1。

我可以通过将名称放入 Excel 电子表格并一个一个地重命名它们来做到这一点。但是我想从列表方式中学习它。

我尝试了以下方法:

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)

它不起作用,只有第一个文件被重命名。

从列表中做到这一点的正确方法是什么?是否存在文件被重命名但顺序不正确的风险?

最佳答案

问题是嵌套循环,看看它是做什么的:

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

关于Python 基础 - 重命名文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25420298/

10-14 18:23