如何重命名在文件末尾添加一个符号的多个文件
由此:
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
谢谢!
答案 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]