python重命名文件夹名并删除额外信息

2024-04-25 13:04:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个长名称的文件夹,其中包括特殊字符(“\”)和创建日期时间。我想要的是在没有日期和时间信息的情况下更改它。在

例如,我有一个名为:

此文件夹名为“龙”,2015年10月7日,10月20日

我想把它改成:

这个由python脚本命名的文件夹。在

有什么建议吗?在


Tags: 脚本文件夹名称信息时间情况命名建议
1条回答
网友
1楼 · 发布于 2024-04-25 13:04:36

这只是你需要做什么的基本大纲,而不是一个完整的解决方案。请确保在文件夹重命名时添加错误检查,并且还需要决定如果试图缩短与正则表达式不匹配的名称,该怎么做。使用this online tester来理解正则表达式。在

from __future__ import print_function

import os
import re

def shortname(s):
    # An ugly regular expression that finds your date time string.
    m = re.search(r'_\d{1,2}_[a-zA-Z]{3}_\d{4}_\d{1,2}_\d{1,2}_\d{1,2}\Z', s)
    # Get your file name without the date time string
    if m is not None:
        return s[:m.start()]
    print("No match found - return original string")
    return s

s = r'C:\test\This_a_folder_with_long_name_20_Oct_2015_07_10_20'
s2 = r'C:\test\This_another_folder_with_long_name_11_Oct_2014_2_1_25'

# Test the output
newname = shortname(s)
print("Long name:", s)
print("New name:", newname)
newname = shortname(s2)
print("Long name:", s2)
print("New name:", newname)
# Only rename if the name is different
if newname != s:
    # You should do error checking before renaming.
    # Does the directory already exist? 
    os.rename(s, newname)

输出:

^{pr2}$

相关问题 更多 >