7

I am trying to append the name of a folder to all filenames within that folder. I have to loop through a parent folder that contain sub folders. I have to do this in Python and not a bat file.

Example is, take these folders:

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

To this

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

I believe its os.rename, but i cant work out how to call the folder name.

Thanks for the advice.

Pablo
  • 4,821
  • 12
  • 52
  • 82
burt46
  • 107
  • 2
  • 2
  • 8
  • You can use `os.walk` to go through the directory and get the names of the files and then `os.rename` to change the names. SO isn't a code writing service. – Harrison Aug 15 '16 at 03:09
  • `os.walk` will give me the filenames in a folder, but it wont give me the name of the folder. If i understood it correctly. – burt46 Aug 15 '16 at 03:13
  • this might help http://techs.studyhorror.com/python-get-last-directory-name-in-path-i-139 – Harrison Aug 15 '16 at 03:19

2 Answers2

12

I would use os.path.basename on the root to find your prefix.

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)))

Before

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

2 directories, 6 files

After

> 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
sberry
  • 128,281
  • 18
  • 138
  • 165
  • Works perfectly. For others not familiar, the "Parent" should have double path spaces, e.g. C:\\test\\dir1 – burt46 Aug 15 '16 at 03:42
5

You can use os.walk to iterate over the directories and then os.rename to rename all the files:

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))
niemmi
  • 17,113
  • 7
  • 35
  • 42