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)
这只是你需要做什么的基本大纲,而不是一个完整的解决方案。请确保在文件夹重命名时添加错误检查,并且还需要决定如果试图缩短与正则表达式不匹配的名称,该怎么做。使用this online tester来理解正则表达式。在
输出:
^{pr2}$相关问题 更多 >
编程相关推荐