2

I am a complete beginner in python. I need to rename a bunch of files with dates in the name. The names all look like:

  • front 7.25.16
  • left 7.25.16
  • right 7.25.16

I would like them to start with the date rather then front, left, or right, so that front 7.25.16 becomes 7.25.16 front.

I have tried using regular expressions and os.walk and I have run into troubles with both. Right now I am just trying to print the file names to prove os.walk is working. Right now my code looks like this:

import re, shutil, os

K = re.compile(r"(\d+.\d+.\d+)")
RE_Date = K.search("front 7.25.16")

for root, dirs, filenames in os.walk("path"):
    for filename in filenames:
        print ("the filename is: " + filename)
    print ("")

Any advice would be greatly appreciated.

3
  • Possible duplicate of Rename Files in Python Commented Jul 29, 2016 at 4:32
  • 2
    You'll need to expand on "I have run into troubles". What specifically isn't working? Commented Jul 29, 2016 at 4:33
  • To begin with os.walk returns a triple of root, dirs, files... Commented Jul 29, 2016 at 4:51

1 Answer 1

1

Check this example to rename file as per your need.

import os

filenames = ["front 7.25.16.jpg", "left 7.25.16.jpg", "right 7.25.16.jpg"]

for file_name in filenames:
    x = file_name.split(' ')[0]
    y = file_name.split(' ')[1]
    new_name = '{} {}{}'.format(os.path.splitext(y)[0], x, os.path.splitext(y)[-1])
    print new_name

output:

7.25.16 front.jpg
7.25.16 left.jpg
7.25.16 right.jpg

In your code your can use os.rename for rename files

import os

for root, dirs, filenames in os.walk("path"):
    for file_name in filenames:
        x = file_name.split(' ')[0]
        y = file_name.split(' ')[1]
        new_name = '{} {}{}'.format(os.path.splitext(y)[0], x, os.path.splitext(y)[-1])
        file_path = os.path.join(root, file_name)
        new_path = os.path.join(root, new_name)
        os.rename(file_name, new_path)
Sign up to request clarification or add additional context in comments.

1 Comment

I am away from my computer right now so I cannot check it, but thank you this looks like it would work. Is there any problem if they are all .jpg?

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.