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 FolderSub1example01.txtexample01.jpgexample01.tifSub2example01.txtexample01.jpgexample01.tif
To this
Parent FolderSub1Sub1_example01.txtSub1_example01.jpgSub1_example01.tifSub2Sub2_example01.txtSub2_example01.jpgSub2_example01.tif
I believe its os.rename, but i cant work out how to call the folder name.
Thanks for the advice.
I would use os.path.basename
on the root to find your prefix.
import osfor root, dirs, files in os.walk("Parent"):if not files:continueprefix = 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.jpg2 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.jpg2 directories, 6 files