python – 选择文件名的特定部分将其移至开头
作者:互联网
我有一些视频课程,我想用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()
解决方法:
鉴于您的示例,这很容易完成,没有正则表达式,如:
码:
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])
标签:python,renaming 来源: https://codeday.me/bug/20190828/1748426.html