我有一个长名称的文件夹,其中包含特殊字符(" _")和创建日期时间。我想要的是在没有日期和时间信息的情况下更改它。
例如,我有一个名为:
的文件夹This_a_folder_with_long_name_20_Oct_2015_07_10_20
我想将其更改为:
This_a_folder_with_long_name by python script。
有什么建议吗?
答案 0 :(得分:1)
这只是您需要做的基本概要,而不是完整的解决方案。确保在文件夹重命名上添加错误检查,如果您尝试缩短与正则表达式不匹配的名称,还需要确定要执行的操作。使用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)
输出:
Long name: C:\test\This_a_folder_with_long_name_20_Oct_2015_07_10_20
New name: C:\test\This_a_folder_with_long_name
Long name: C:\test\This_another_folder_with_long_name_11_Oct_2014_2_1_25
New name: C:\test\This_another_folder_with_long_name