编写脚本以重命名不正确的文件

时间:2019-05-17 13:06:54

标签: python-3.x windows

所以我正在尝试编写一个脚本,该脚本将在给定路径中搜索包含例如“ Disqualification_of_counsel-.pdf.~tmp@d#260904795^9ff1be71-a06c-4a48-a985-6acd63080bfb”的文件文件名到Disqualification_of_counsel.pdf,结尾没有添加垃圾,对于以docx或doc结尾的文件也是如此。最后,我希望它把输出写出来,这样我可以看到脚本已经走了多远。我仍在学习python,因此请原谅我脚本不完整,因为我有些迷路。任何帮助将不胜感激。

到目前为止,我已经获得了需要查看的基本脚本,请原谅我对这一主题的知识不足。

import os
from pathlib import Path
def main():

    print ("Please enter where the files are located")
    user = input()
    path = Path(_file_).parent.absolute()
    filenames = os.listdir(path)

if path.exist() == user:
    print(""Running script"")
for filename in filenames:
    os.rename(filename, filename.replace("", "")

1 个答案:

答案 0 :(得分:0)

尝试一下:

import os
from pathlib import Path
import re

user = input("Please enter where the files are located")
path = Path(user).absolute()
if path.exists():
    print("Running script")
    filenames = os.listdir(path)

    for filename in filenames:
        os.rename(os.path.join(path, filename), 
                  os.path.join(path, re.sub(r"([^\.]+\.[^\.]+).*", r"\1", filename)))

    print("done")

else:
    print("does not exist")
  

re.sub时正在使用正则表达式。如果您不熟悉正则表达式,请查看以下链接:
  https://regexr.com/
  https://docs.python.org/3.7/library/re.html