开发者

Changing Directory Names in Python [closed]

开发者_如何学C It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜