如何在python中更改文件夹名称? [英] 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.
例如,在文件夹 Test 中,我有:
As an example, in the folder Test, i have:
C:/Test/John Smith
C:/Test/Fred Jones
C:/Test/Ben Jack Martin
我想做这个:
C:/Test/Smith, John
C:/Test/Jones, Fred
C:/Test/Martin, Ben Jack
我用 os.rename 尝试了一些东西,但我似乎无法让它在不同的名字长度下工作,而且我不知道如何在姓氏中插入逗号.
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.
另外,一些文件夹名称已经是正确的格式,所以我需要在重命名时跳过这些文件夹.我认为你可以通过添加一个 if 来做到这一点,这样如果文件夹名称包含逗号,它就会继续.
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.
推荐答案
您可以使用 os.listdir
和 os.path> 功能:
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))
这篇关于如何在python中更改文件夹名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!