问题描述 投票:0回答:1

我正在尝试使用下面的脚本重命名文件夹中的所有文件,但是重命名所有文件在文件夹中命名其删除文件。

import os
i=0
for file in os.listdir():  
    src=file 
    dst="gain"+str(i)+".tfw"  
    dst = 'D:\Share' + dst  
    os.rename(src,dst) 
    i+= 1 

没有给我错误。

python
1个回答
0
投票

您可以在这种情况下使用pathlib,我认为它看起来更好

from pathlib import Path
root_dir = Path('/path/to/folder')
for i, f in enumerate(root_dir.iterdir()):
     f.rename(f.parent / "gain{}.tfw".format(i))

也不要覆盖文件变量名称,这是不正确的做法

© www.soinside.com 2019 - 2024. All rights reserved.