0

Hi guys have a problem with renaming a set of files in separate folder in python. i have a folder structure like

images/p_0/aaa.jpg,bbb.jpg
images/p_1/aaa.jpg,bbb.jpg
images/p_2/aaa.jpg,bbb.jpg

I need to rename these jpg to like

images/p_0/A-1.jpg,B-1.jpg
images/p_1/A-2.jpg,B-2.jpg
images/p_2/A-3.jpg,B-3.jpg

and i am using the os.rename method. I just don't get how to cycle through the folders and find the image and rename it.

4 Answers 4

3

Use os.walk and os.rename.

import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        #Rename your files and use os.path.join(root, name)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use os.listdir() to get all the files in some directory. You might also want to look through the rest of the os module documentation.

3 Comments

Yes i tried that out it only lists the dir in the images folder i need to find the files inside the dirs and rename them
So have two loops: for dirname in os.listdir("images"): for filename in os.listdir("images/" + dirname"): do_something()
Karmastan, you should use os.path.join("images", dirname) instead of direct string concatenation.
0

Take a look at os.listdir or os.walk, if you have a nested directory structure.

#!/usr/bin/env python

import os

# list all files
for filename in os.listdir('.'):
    print filename # do something with filename ...

def is_image(filename):
    """ Tiny filter function. """
    return filename.endswith(".jpg") or filename.endswith(".png")

# only consider files, which pass the `is_image` filter
for filename in filter(is_image, os.listdir('.')):
    print filename # do something with filename ...

Comments

0

In addition to os.walk(), glob.glob() might be useful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.