选择文件名的特定部分将其移至开头

时间:2018-02-18 17:42:21

标签: python renaming

我有一些视频课程,我想用Python以特定的方式重命名。这是一个示例文件名:

3D Graphics - Crash Course Computer Science #27-TEAtmCYYKZA.en"

我想选择" 27"并将其移动到文件名的开头,并删除" Crash Course Computer Science#"和" -TEAtmCYYKZA.en"完全是一部分。所以,我想要的输出是:

27 - 3D Graphics

另外两个例子:

Advanced CPU Designs - Crash Course Computer Science #9-rtAlC5J1U40
Boolean Logic & Logic Gates - Crash Course Computer Science #3-gI-qXk7XojA

到:

9 - Advanced CPU Designs
3 - Boolean Logic & Logic Gates

我知道如何删除部分,但我可以找到如何选择"#number"子。我发现了一个.split()函数,但我再也看不出它是如何使它工作的。

这是我到目前为止写的内容,但我已经陷入了早期阶段。

import os

def rename():
    file_list = os.listdir(r"D:\Downloads\New folder")

    for file_name in file_list:
        os.rename(file_name, )

rename() 

2 个答案:

答案 0 :(得分:4)

考虑到你的例子,这很容易做到,没有正则表达式,如:

代码:

def transform_name(filename):
    number = filename.split('#')[1].split('-')[0].strip()
    name = filename.split('-')[0].strip()
    return '{} - {}'.format(number, name)

在示例中使用:

os.rename(existing_filename, transform_name(existing_filename))

测试代码:

test_in = (
    "3D Graphics - Crash Course Computer Science #27-TEAtmCYYKZA.en",
    "Advanced CPU Designs - Crash Course Computer Science #9-rtAlC5J1U40",
    "Boolean Logic & Logic Gates - Crash Course Computer Science #3-gI-qXk7XojA",
)

desired_out = (
    "27 - 3D Graphics",
    "9 - Advanced CPU Designs",
    "3 - Boolean Logic & Logic Gates",
)

for data in zip(test_in, desired_out):
    assert transform_name(data[0]) == data[1], "{} != {}".format(
        transform_name(data[0]), data[1])

答案 1 :(得分:1)

我喜欢@StephenRauch没有正则表达式的答案,这只是为了显示另一个选项。

>>> import re
>>> REGEX = re.compile(r'(?P<name>.+) - .+ #(?P<number>\d+)')
>>> test_in = (
...     "3D Graphics - Crash Course Computer Science #27-TEAtmCYYKZA.en",
...     "Advanced CPU Designs - Crash Course Computer Science #9-rtAlC5J1U40",
...     "Boolean Logic & Logic Gates - Crash Course Computer Science #3-gI-qXk7XojA",
... )
>>> for line in test_in:
...     m = REGEX.match(line)
...     if m:
...         print('{number} - {name}'.format(**m.groupdict()))
... 
27 - 3D Graphics
9 - Advanced CPU Designs
3 - Boolean Logic & Logic Gates