python檔名替換例項
阿新 • • 發佈:2019-02-07
看了一段時間的python了,今天以一個小程式為例整合一下近幾章的知識點。
環境:pycharm + python3.6
程式的主要功能是將檔名中包含美國風格的日期(MM-DD-YYYY)轉換為歐洲風格的日期(DD-MM-YYYY)
簡單列舉了下主要的步驟:
(1)建立查詢日期的正則表示式
(2)在給定路徑中遍歷檔名
(3)跳過不含日期的檔案
(4)獲取含日期的檔名中日期的各個部分
(5)將檔名改成歐洲格式:DD-MM-YYYY
(6)獲取檔案的路徑名
(7)移動並重命名檔案
這裡用到的包:shutil, re, os
import shutil, re, os
接下來建立匹配日期的正則表示式:
date_re = re.compile(r'''(.*?) #all text before the date
((0|1)?\d)- #one or two digits for the month
((0|1|2|3)?\d)- #one or two digits for the day
((19|20)\d\d) #four digits for the year
(.*?)$ #all text after the date
''', re.VERBOSE)
在給定的路徑中遍歷檔名,對含有日期格式的檔名進行替換
file_path = 'E:\\test_file\\' #set the file path
for amer_filename in os.listdir(file_path):
str_date = date_re.search(amer_filename)
#TODO: 跳過不含日期的檔案
if str_date == None:
continue
#TODO: 獲取含日期的檔名中日期的各個部分
before_part = str_date.group(1)
month_part = str_date.group(2)
day_part = str_date.group(4)
year_part = str_date.group(6)
after_part = str_date.group(8)
#TODO: 將檔名改成歐洲格式:DD-MM-YYYY
euro_filename = before_part + day_part + '-' + month_part + '-' + year_part + after_part;
#TODO: 獲取檔案的路徑名
abs_workingDir = os.path.abspath(file_path)
amer_filename = os.path.join(abs_workingDir, amer_filename)
euro_filename = os.path.join(abs_workingDir, euro_filename)
#TODO: 重新命名檔案
print('Renaming "%s" to "%s"' % (amer_filename, euro_filename))
shutil.move(amer_filename, euro_filename)