简体   繁体   English

如何使用python重命名每个文件夹中以'1'开头的数字重命名文件?

[英]how to rename files in multiple folders numerically starting with '1' each folder using python?

i'm trying to rename files numerically in multiple folders but it seems that the count continues to run through all the files and not starting from '1' each folder. 我正在尝试以数字方式重命名多个文件夹中的文件,但似乎计数继续遍历所有文件,而不是从每个文件夹的“ 1”开始。 what should i do? 我该怎么办?

i have tried the following code: 我尝试了以下代码:

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

This should work: 这应该工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python重命名文件夹中的多个文件? - How does one rename multiple files within folders using python? 如何使用python脚本重命名文件夹中的多个文件 - How to rename multiple files in a folder using python script Python:重命名以“#”开头的多个文件 - Python: Rename multiple files starting with a “#” Python:识别文件夹结构中的数字名称文件夹 - Python: Identifying numerically names folders in a folder structure 如何使用python将多个文件夹中的多个文件复制到一个文件夹中? - How to copy multiple files from multiple folders into one folder using python? 如何使用 python 脚本重命名文件夹中包含日期的多个 netCDF 文件? - How to rename multiple netCDF files in a folder with dates inside these using python script? 如何使用 Python 读取多个文件夹中的文件 - How to read files in multiple folders using Python 如何使用Python合并一个文件夹及其子文件夹中的多个Excel文件 - How to merge multiple Excel files from a folder and it's sub folders using Python 在文件夹和子文件夹中搜索多个文件 python - Search multiple files in folder and sub folders python Python - 如何读取以 xyz 开头的文件夹中的多个文件? - Python - How do you read multiple files in a folder starting by xyz?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM