简体   繁体   English

重命名子文件夹python中文件名的一部分

[英]Rename part of filenames in sub-folders python

I have to rename images in main directory with contains sub-folders, script with I using right now do some work but not exactly what I need: I can't find a way to do it properly, now i have it: 我必须使用包含子文件夹的名称重命名主目录中的图像,现在我使用的脚本可以完成一些工作,但并不能完全满足我的需要:我现在找不到合适的方法:

maindir #my example origin
├── Sub1
│   ├── example01.jpg
│   ├── example02.jpg
│   └── example03.jpg
└── Sub2
    ├── example01.jpg
    ├── example02.jpg
    └── example03.jpg

My script do that: 我的脚本这样做:

maindir
├── Sub1
│   ├── Sub1_example01.jpg
│   ├── Sub1_example02.jpg
│   └── Sub1_example03.jpg
└── Sub2
    ├── Sub2_example01.jpg
    ├── Sub2_example02.jpg
    └── Sub2_example03.jpg

And I would like to get it :replace a letters in my filenames by my sub-folder name and keep the origin numbers of my jpg: 我想得到它:用子文件夹名称在文件名中替换字母,并保留jpg的原始编号:

maindir
├── Sub1
│   ├── Sub1_01.jpg
│   ├── Sub1_02.jpg
│   └── Sub1_03.jpg
└── Sub2
    ├── Sub2_01.jpg
    ├── Sub2_02.jpg
    └── Sub2_03.jpg

there is my code 4 witch I using: 我使用的是我的代码4女巫:

from os import walk, path, rename
parent = ("F:\\PS\\maindir")
for dirpath, _, files in walk(parent):
    for f in files:
        rename(path.join(dirpath, f), path.join(dirpath, path.split(dirpath)[-1] + '_' + f))

what I have to change overhere to get my result??? 我必须在这里更改才能得到我的结果???

instead of that line: 而不是该行:

rename(path.join(dirpath, f), path.join(dirpath, path.split(dirpath)[-1] + '_' + f))

generate a new name using str.replace : 使用str.replace生成一个新名称:

newf = f.replace("example",os.path.basename(dirpath)+"_")

then 然后

rename(path.join(dirpath, f), path.join(dirpath,newf))

of course if you don't know the extension or the "prefix" of the input file, and only want to keep the number & extension, there's a way: 当然,如果您不知道输入文件的扩展名或“前缀”,而只想保留数字和扩展名,则可以采用以下方法:

import re
number = (re.findall("\d+",f) or ['000'])[0]

this extracts the number from the name, and if not found, issues 000 . 这将从名称中提取数字,如果找不到,则发出000

Then rebuild newf with the folder name, the extracted number & the original extension: 然后使用文件夹名称,提取的号码和原始扩展名重建newf

newf = "{}_{}.{}".format(os.path.basename(dirpath),number,os.path.splitext(f)[1])

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM