如何在python中更改文件夹名?

2024-05-13 11:59:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有多个文件夹,每个文件夹都有一个人的名字,名字在前,姓氏在后。我想更改文件夹名称,以便姓氏后跟逗号,然后紧跟第一个名称。

例如,在“测试”文件夹中,我有:

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尝试了一些东西,但是我似乎无法使它在不同的名称长度下工作,我不知道如何在姓氏中插入逗号。

另外,一些文件夹名的格式已经正确,因此在重命名期间我需要跳过这些文件夹。我想你可以添加一个if,这样如果文件夹名包含逗号,它将继续。

否则,姓氏将始终是文件夹名称中的最后一个单词。

谢谢你的帮助。


Tags: test文件夹名称osfred名字johnmartin
3条回答
os.rename("Joe Blow", "Blow, Joe")

对我来说似乎很管用。哪一部分你有问题?

我喜欢phihag关于rpartition()的建议,我认为以下几点基本上是等价的:

>>> 'first second third fourth'.rpartition(' ')
('first second third', ' ', 'fourth')
>>> 'first second third fourth'.rsplit(None, 1)
['first second third', 'fourth']

我更喜欢rsplit(),因为我不想关心分隔符,但我也可以看到它有点冗长。

设置

>>> base = 'C:\\Test'
>>> os.makedirs(os.path.join(base, 'John Smith'))
>>> os.makedirs(os.path.join(base, 'Fred Jones'))
>>> os.makedirs(os.path.join(base, 'Ben Jack Martin'))
>>> os.listdir(base)
['Ben Jack Martin', 'Fred Jones', 'John Smith']

解决方案

>>> for old_name in os.listdir(base):
    # [::-1] is slice notation for "reverse"
    new_name = ', '.join(old_name.rsplit(None, 1)[::-1])
    os.rename(os.path.join(base, old_name),
          os.path.join(base, new_name))


>>> os.listdir(base)
['Jones, Fred', 'Martin, Ben Jack', 'Smith, John']

您可以使用^{}os.path函数直接写出:

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))

相关问题 更多 >