在進行數據集處理時,發現需要將原文件夾名稱修改,這裏舉一個例子,我的原文件夾名稱爲1、2、3、4…,需要修改爲總字符數爲4位的名稱,即:0001、0002、0003、0004…
下面是python代碼實現批量修改:
import os
def replaceDirName(rootDir):
dirs = os.listdir(rootDir)
# 遍歷每一個文件夾
for dir in dirs:
# 輸出老文件夾的名字
# print('oldname is:' + dir)
# 主要目的是在數字統一爲4位,不夠的前面補0
temp = "%04d" % int(dir)
# 老文件夾的名字
oldname = os.path.join(rootDir, dir)
# 新文件夾的名字
newname = os.path.join(rootDir, temp)
# 用新文件夾的名字替換老文件夾的名字
# rename(*args, **kwargs):重命名文件或目錄
os.rename(oldname, newname)
if __name__ == '__main__':
rootdir = 'F:/DenseNet161_Car/data/test'
replaceDirName(rootdir)
下面是老文件夾名字的輸出:
....................
oldname is:43
oldname is:44
oldname is:45
oldname is:46
oldname is:47
oldname is:48
..........................
修改後新文件夾名字: