python 将文件夹名称附加到所有子文件夹中的文件名

python append folder name to filenames in all sub folders

我正在尝试将文件夹的名称附加到该文件夹​​中的所有文件名。我必须遍历包含子文件夹的父文件夹。我必须在 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 to iterate over the directories and then 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))

我会在根上使用 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