Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

rename - How to change folder names in python?

I have multiple folders each with the name of a person, with the first name(s) first and the surname last. I want to change the folder names so that the surname is first followed by a comma and then the first name(s) follow.

As an example, in the folder Test, i have:

C:/Test/John Smith
C:/Test/Fred Jones
C:/Test/Ben Jack Martin

and i want to make this:

C:/Test/Smith, John
C:/Test/Jones, Fred
C:/Test/Martin, Ben Jack

I tried some things with os.rename but i couldn't seem to make it work with the varying name length, and i wasn't sure how to insert the comma into the surname.

Also, some of the folder names are already in the correct form, so i need to skip these folders during the renaming. I think you can do this by just adding an if, so that if the folder name contains a comma it will continue.

Otherwise, the surname will always be the last word in the folder name.

Thanks for any help you can provide.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can write it out fairly straight-forward, using os.listdir and the os.path functions:

import os
basedir = 'C:/Test'
for fn in os.listdir(basedir):
  if not os.path.isdir(os.path.join(basedir, fn)):
    continue # Not a directory
  if ',' in fn:
    continue # Already in the correct form
  if ' ' not in fn:
    continue # Invalid format
  firstname,_,surname = fn.rpartition(' ')
  os.rename(os.path.join(basedir, fn),
            os.path.join(basedir, surname + ', ' + firstname))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...