将文件夹名称附加到所有子文件夹中的文件名中,使用Python实现。

7

我将尝试在文件夹名称后附加所有文件名。我必须遍历包含子文件夹的父文件夹。我必须使用Python而不是bat文件。

例如,将这些文件夹:

Parent Folder
 Sub1
  example01.txt
  example01.jpg
  example01.tif
 Sub2
  example01.txt
  example01.jpg
  example01.tif

对于这个问题

Parent Folder
 Sub1
  Sub1_example01.txt
  Sub1_example01.jpg
  Sub1_example01.tif
 Sub2
  Sub2_example01.txt
  Sub2_example01.jpg
  Sub2_example01.tif

我相信应该使用os.rename函数,但我不知道如何调用文件夹的名称。
谢谢你的建议。

你可以使用 os.walk 遍历目录并获取文件名,然后使用 os.rename 更改名称。SO 不是一个代码编写服务。 - Harrison
os.walk会给我文件夹中的文件名,但不会给我文件夹的名称。如果我理解正确的话。 - burt46
这可能会有所帮助 http://techs.studyhorror.com/python-get-last-directory-name-in-path-i-139 - Harrison
2个回答

12

我会在根目录使用os.path.basename来找到你的前缀。

import os

for root, dirs, files in os.walk("Parent"):
    if not files:
        continue
    prefix = os.path.basename(root)
    for f in files:
        os.rename(os.path.join(root, f), os.path.join(root, "{}_{}".format(prefix, f)))

之前

> tree Parent
Parent
├── Sub1
│   ├── example01.jpg
│   ├── example02.jpg
│   └── example03.jpg
└── Sub2
    ├── example01.jpg
    ├── example02.jpg
    └── example03.jpg

2 directories, 6 files

之后

> tree Parent
Parent
├── Sub1
│   ├── Sub1_example01.jpg
│   ├── Sub1_example02.jpg
│   └── Sub1_example03.jpg
└── Sub2
    ├── Sub2_example01.jpg
    ├── Sub2_example02.jpg
    └── Sub2_example03.jpg

2 directories, 6 files

完美运行。对于不熟悉的人,"Parent" 应该有双路径空格,例如 C:\test\dir1。 - burt46

5
您可以使用 os.walk 遍历文件夹,然后使用 os.rename 重命名所有文件:
from os import walk, path, rename

for dirpath, _, files in walk('parent'):
    for f in files:
        rename(path.join(dirpath, f), path.join(dirpath, path.split(dirpath)[-1] + '_' + f))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接