python批量修改文件名的實(shí)現(xiàn)代碼
更新時(shí)間:2014年09月01日 16:09:48 投稿:mdxy-dxy
這篇文章主要介紹了python批量修改文件名的實(shí)現(xiàn)代碼,需要的朋友可以參考下
#coding:utf-8
#批量修改文件名
import os import re import datetime
re_st = r'(\d+)\+\s?\((\d+)\)'
#用于匹配舊的文件名,需含分組 re_match_old_file_name = re.compile(re_st)
#要修改的目錄 WORKING_PATH = r'F:\Gallery'
#----------------------------------------------------------------------
def rename_fomat(name):
"""
文件重命名格式組織模塊(一般修改這里就可以了)
NOTE:返回類型必須是unicode
"""
if name:
re_rn = re_match_old_file_name.findall(name)
if re_rn and re_rn != []:
re_rn = re_rn[0]
num = int(re_rn)
new_nm = u'NO.%04d' % ( num)
return new_nm
#----------------------------------------------------------------------
def logs(error):
"""
錯(cuò)誤記錄
"""
log = ''
LOG_FILE = open(r'./log.txt', 'a')
live_info ="""
==========
Time : %s
title : %s
Path :
%s
==========
""" % (
datetime.datetime.now(),
str(error['title']),
str(error['index']),
)
log += live_info
errors = error['error_paths']
for item in errors:
item = '%s\n' % item
log += item
log = log.encode('utf-8')
try:
LOG_FILE.write(log)
except IOError:
print u'寫入日志失敗'
finally:
LOG_FILE.close()
#----------------------------------------------------------------------
def rename(old, new):
"""
文件重命名模塊
return:
0:rename success
1:the new path is exists
-1:rename failed
"""
if not os.path.exists(new):
try:
os.renames(old, new)
return 0
except IOError:
print 'path error:', new
return -1
else:
return 1
#----------------------------------------------------------------------
def get_dirs(path):
"""
獲取目錄列表
"""
if os.path.exists(path):
return os.listdir(path)
else:
return -1
#----------------------------------------------------------------------
def get_input_result(word, choice):
"""
獲取正確的輸入結(jié)果
"""
correct_result = set(choice)
word = '===%s?\n[in]:' % (word)
while True:
in_choice = raw_input(word)
if in_choice in correct_result: return in_choice
#----------------------------------------------------------------------
def batch_rename(index, dirs = []):
"""
批量修改文件
"""
index = unicode(index)
errors = []
if dirs == []:
dirs = get_dirs(path = index)
if dirs and dirs != []:
for item in dirs:
item = unicode(item)
new_name = rename_fomat(item)
if new_name :
old_pt = u'%s\\%s'% (index, item)
new_pt = u'%s\\%s'% (index, new_name)
res_rn = rename(old_pt, new_pt)
if res_rn != 0:
errors.append(item)
else:
errors.append(item)
if errors and errors != []:
print 'Rename Failed:'
logs({
'index': index,
'title': 'Rename Failed' ,
'error_paths': errors,
})
for i, item in enumerate(errors):
print item, '|',
if i % 5 == 4:
print ''
print ''
else:
return -1
#----------------------------------------------------------------------
def batch_rename_test(index):
"""
測(cè)試
返回過濾結(jié)果
"""
index = unicode(index)
errors = []
correct = []
dirs = get_dirs(path = index)
if dirs and dirs != []:
for x, item in enumerate(dirs):
item = unicode(item)
new_name = rename_fomat(item)
if new_name :
correct.append(item)
old_pt = u'%s\\%s'% (index, item)
new_pt = u'%s\\%s'% (index, new_name)
print '[%d]O: %s' % ( x + 1, old_pt)
print '[%d]N: %s' % ( x + 1, new_pt)
else:
errors.append(item)
if errors and errors != []:
print 'Not Match:'
logs({
'index': index,
'title': 'Not Match',
'error_paths': errors,
})
for i, item in enumerate(errors):
print item, '|',
if i % 5 == 4:
print ''
print ''
return correct
#----------------------------------------------------------------------
def manage(index):
"""
程序組織塊
"""
file_filter = batch_rename_test(index)
do_choice = get_input_result(
word = 'Do with this(y / n)',
choice = ['y', 'n']
)
if do_choice == 'y':
batch_rename(index, dirs= file_filter)
print 'Finished !'
if __name__ == '__main__':
path = WORKING_PATH
manage(index = path)
相關(guān)文章
詳解利用Pandas求解兩個(gè)DataFrame的差集,交集,并集
這篇文章主要和大家講解一下如何利用Pandas函數(shù)求解兩個(gè)DataFrame的差集、交集、并集,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-07-07
django認(rèn)證系統(tǒng) Authentication使用詳解
這篇文章主要介紹了django認(rèn)證系統(tǒng) Authentication使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
如何實(shí)現(xiàn)更換Jupyter Notebook內(nèi)核Python版本
這篇文章主要介紹了如何實(shí)現(xiàn)更換Jupyter Notebook內(nèi)核Python版本,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
Python集中化管理平臺(tái)Ansible介紹與YAML簡(jiǎn)介
這篇文章主要介紹了Python集中化管理平臺(tái)Ansible介紹與YAML,簡(jiǎn)單說明了集中化管理平臺(tái)Ansible的功能與YAML語言的基本語法與基本使用技巧,需要的朋友可以參考下2019-06-06
Python 類方法和實(shí)例方法(@classmethod),靜態(tài)方法(@staticmethod)原理與用法分析
這篇文章主要介紹了Python 類方法和實(shí)例方法(@classmethod),靜態(tài)方法(@staticmethod),結(jié)合實(shí)例形式分析了Python 類方法和實(shí)例方法及靜態(tài)方法相關(guān)原理、用法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2019-09-09
centos 安裝Python3 及對(duì)應(yīng)的pip教程詳解
這篇文章主要介紹了centos 安裝Python3 及對(duì)應(yīng)的pip的教程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-06-06
Python RPA自動(dòng)化機(jī)器人模擬鼠標(biāo)鍵盤
這篇文章主要介紹了Python RPA自動(dòng)化機(jī)器人模擬鼠標(biāo)鍵盤,RPA,全稱為Robotic Process Automation,即機(jī)器人流程自動(dòng)化。我們可以利用RPA技術(shù)將工作中可重復(fù)的部分流程化,讓機(jī)器替我們完成這一工作2023-02-02
詳解python腳本自動(dòng)生成需要文件實(shí)例代碼
這篇文章主要介紹了詳解python腳本自動(dòng)生成需要文件實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-02-02

