Reputation: 307
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.
Upvotes: 2
Views: 204
Reputation: 7142
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)
Upvotes: 1