如何重命名多个文件,在文件末尾添加一个符号

时间:2018-01-22 07:22:58

标签: python-3.x multiple-files

如何重命名在文件末尾添加一个符号的多个文件

由此:

New Text Document.txt
New Text Document (2).txt
New Text Document (3).txt
New Text Document (4).txt

对此:

New Text Document1.txt
New Text Document2.txt
New Text Document3.txt
New Text Document4.txt

谢谢!

1 个答案:

答案 0 :(得分:0)

输入

from os.path import splitext


file_list = ["New Text Document.txt", "New Text Document (2).txt",
             "New Text Document (3).txt", "New Text Document (4).txt"]

使用

获得所需的输出
def parse(file, no):
    body, ext = splitext(file)
    new_body_str = ' '.join(body.split()[:3])
    return f"{new_body_str}{no}{ext}"

output_list = [parse(filename, no+1) for no, filename in enumerate(file_list)]

如果您需要此功能来处理除New Text Document之外的其他文件,请使用正则表达式而不是body.split()[:3]