【问题标题】:how to rename files in multiple folders numerically starting with '1' each folder using python?如何使用python以数字方式重命名多个文件夹中的文件,每个文件夹以“1”开头?
【发布时间】:2019-09-11 10:49:17
【问题描述】:

我正在尝试以数字方式重命名多个文件夹中的文件,但计数似乎继续遍历所有文件,而不是从每个文件夹的“1”开始。我该怎么办?

我尝试了以下代码:

for folderName, subfolders, filenames in os.walk(path):
    for f in filenames:
        f_name, f_ext = os.path.splitext(f)
        f_name = str(count)
        count = count + 1

  new_name = '{}{}'.format(f_name, f_ext)          
  os.rename(os.path.join(folderName,f),os.path.join(folderName,new_name))


i expect the output renaming of the files to be:
files in folder 1: 1.tif, 2.tif, 3.tif, 4.tif 
files in folder 2: 1.tif, 2.tif, 3.tif
files in folder 3: 1.tif, 2.tif, 3.tif, 4.tif 

but the actual outcome is:
files in folder 1: 1.tif, 2.tif, 3.tif, 4.tif 
files in folder 2: 5.tif, 6.tif, 7.tif
files in folder 3: 8.tif, 9.tif, 10.tif, 11.tif

【问题讨论】:

    标签: python count rename subdirectory numeric


    【解决方案1】:

    这应该可行:

    for folderName, subfolders, filenames in os.walk(path):
        count = 1   # << -- here are the changes
        for f in filenames:
            f_name, f_ext = os.path.splitext(f)
            f_name = str(count)
            count += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-05
      • 2015-08-26
      • 2018-06-18
      • 1970-01-01
      • 2018-04-26
      • 2015-09-18
      • 2019-07-23
      • 1970-01-01
      相关资源
      最近更新 更多