Changing Directory Names in Python [closed]
I'm trying to change how my directories and files within them are all labelled. Currently the system is "082411-SomeNameHere" (mmddyy-Title) and I'd like to change it to "110824-SomeNameHere".
I know the moving of the numbers is fairly simple, but I'm mostly unsure on how to access the names in the directories and change all them.
Suggestions?
Try this:
import os, re, shutil
r = re.compile(r'^([0-9]{2})([0-9]{2})([0-9]{2})-(.*)$')
for root, dirs, files in os.walk('/path/to/topdir'):
for filename in files:
match = r.match(filename)
if match:
newfilename = match.group(3) + match.group(1) + match.group(2) + '-' + match.group(4)
newfilename = os.path.join(root, newfilename)
oldfilename = os.path.join(root, filename)
# Rename oldfilename to newfilename
shutil.move(oldfilename, newfilename)
Basically this traverses the directory structure using os.walk
, looks for files that appear to have the old naming convention, extracts the parts out, and does a rename with shutil.move
.
You want os.walk
for the directory and file traversal.
And you can use shutil.move
for the file renaming.
import os
import shutil
for dirpath, dirs, files in os.walk(os.curdir):
for filename in files:
shutil.move( # alternative: `os.rename`
os.path.join(dirpath, filename),
os.path.join(dirpath, filename_with_changes),
)
"...the moving of the numbers is fairly simple" so I leave that to you :D
Welcome to StackOverflow.
精彩评论