python append folder name to filenames in all sub folders

2024/10/7 18:29:49

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.

Answer

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
https://en.xdnf.cn/q/70211.html

Related Q&A

When ruamel.yaml loads @dataclass from string, __post_init__ is not called

Assume I created a @dataclass class Foo, and added a __post_init__ to perform type checking and processing.When I attempt to yaml.load a !Foo object, __post_init__ is not called.from dataclasses import…

How is the python module search path determined on Mac OS X?

When a non built-in module is imported, the interpreter searches in the locations given by sys.path. sys.path is initialized from these locations (http://docs.python.org/library/sys.html#sys.path):the …

Apply Mask Array 2d to 3d

I want to apply a mask of 2 dimensions (an NxM array) to a 3 dimensional array (a KxNxM array). How can I do this?2d = lat x lon 3d = time x lat x lonimport numpy as npa = np.array([[[ 0, 1, 2],[ 3,…

Server Side Google Markers Clustering - Python/Django

After experimenting with client side approach to clustering large numbers of Google markers I decided that it wont be possible for my project (social network with 28,000+ users).Are there any examples …

Tensorflow numpy image reshape [grayscale images]

I am trying to execute the Tensorflow "object_detection_tutorial.py" in jupyter notebook, with my trained neural network data but it throws a ValueError. The file mentioned above is part of S…

Merge numpy arrays returned from loop

I have a loop that generates numpy arrays:for x in range(0, 1000):myArray = myFunction(x)The returned array is always one dimensional. I want to combine all the arrays into one array (also one dimensio…

Play mp3 using Python, PyQt, and Phonon

I been trying all day to figure out the Qts Phonon library with Python. My long term goal is to see if I could get it to play a mms:// stream, but since I cant find an implementation of this done anywh…

Python dictionary keys(which are class objects) comparison with multiple comparer

I am using custom objects as keys in python dictionary. These objects has some default hash and eq methods defined which are being used in default comparison But in some function i need to use a diffe…

How can I make np.save work for an ndarray subclass?

I want to be able to save my array subclass to a npy file, and recover the result later.Something like:>>> class MyArray(np.ndarray): pass >>> data = MyArray(np.arange(10)) >>&g…

With ResNet50 the validation accuracy and loss is not changing

I am trying to do image recognition with ResNet50 in Python (keras). I tried to do the same task with VGG16, and I got some results like these (which seem okay to me): resultsVGG16 . The training and v…