当前位置:Gxlcms > Python > python批量修改文件名的实现代码

python批量修改文件名的实现代码

时间:2021-07-01 10:21:17 帮助过:63人阅读

  1. #coding:utf-8
  2. #批量修改文件名
  3. import os import re import datetime
  4. re_st = r'(\d+)\+\s?\((\d+)\)'
  5. #用于匹配旧的文件名,需含分组 re_match_old_file_name = re.compile(re_st)
  6. #要修改的目录 WORKING_PATH = r'F:\Gallery'
  7. #----------------------------------------------------------------------
  8. def rename_fomat(name):
  9. """
  10. 文件重命名格式组织模块(一般修改这里就可以了)
  11. NOTE:返回类型必须是unicode
  12. """
  13. if name:
  14. re_rn = re_match_old_file_name.findall(name)
  15. if re_rn and re_rn != []:
  16. re_rn = re_rn[0]
  17. num = int(re_rn)
  18. new_nm = u'NO.%04d' % ( num)
  19. return new_nm
  20. #----------------------------------------------------------------------
  21. def logs(error):
  22. """
  23. 错误记录
  24. """
  25. log = ''
  26. LOG_FILE = open(r'./log.txt', 'a')
  27. live_info ="""
  28. ==========
  29. Time : %s
  30. title : %s
  31. Path :
  32. %s
  33. ==========
  34. """ % (
  35. datetime.datetime.now(),
  36. str(error['title']),
  37. str(error['index']),
  38. )
  39. log += live_info
  40. errors = error['error_paths']
  41. for item in errors:
  42. item = '%s\n' % item
  43. log += item
  44. log = log.encode('utf-8')
  45. try:
  46. LOG_FILE.write(log)
  47. except IOError:
  48. print u'写入日志失败'
  49. finally:
  50. LOG_FILE.close()
  51. #----------------------------------------------------------------------
  52. def rename(old, new):
  53. """
  54. 文件重命名模块
  55. return:
  56. 0:rename success
  57. 1:the new path is exists
  58. -1:rename failed
  59. """
  60. if not os.path.exists(new):
  61. try:
  62. os.renames(old, new)
  63. return 0
  64. except IOError:
  65. print 'path error:', new
  66. return -1
  67. else:
  68. return 1
  69. #----------------------------------------------------------------------
  70. def get_dirs(path):
  71. """
  72. 获取目录列表
  73. """
  74. if os.path.exists(path):
  75. return os.listdir(path)
  76. else:
  77. return -1
  78. #----------------------------------------------------------------------
  79. def get_input_result(word, choice):
  80. """
  81. 获取正确的输入结果
  82. """
  83. correct_result = set(choice)
  84. word = '===%s?\n[in]:' % (word)
  85. while True:
  86. in_choice = raw_input(word)
  87. if in_choice in correct_result: return in_choice
  88. #----------------------------------------------------------------------
  89. def batch_rename(index, dirs = []):
  90. """
  91. 批量修改文件
  92. """
  93. index = unicode(index)
  94. errors = []
  95. if dirs == []:
  96. dirs = get_dirs(path = index)
  97. if dirs and dirs != []:
  98. for item in dirs:
  99. item = unicode(item)
  100. new_name = rename_fomat(item)
  101. if new_name :
  102. old_pt = u'%s\\%s'% (index, item)
  103. new_pt = u'%s\\%s'% (index, new_name)
  104. res_rn = rename(old_pt, new_pt)
  105. if res_rn != 0:
  106. errors.append(item)
  107. else:
  108. errors.append(item)
  109. if errors and errors != []:
  110. print 'Rename Failed:'
  111. logs({
  112. 'index': index,
  113. 'title': 'Rename Failed' ,
  114. 'error_paths': errors,
  115. })
  116. for i, item in enumerate(errors):
  117. print item, '|',
  118. if i % 5 == 4:
  119. print ''
  120. print ''
  121. else:
  122. return -1
  123. #----------------------------------------------------------------------
  124. def batch_rename_test(index):
  125. """
  126. 测试
  127. 返回过滤结果
  128. """
  129. index = unicode(index)
  130. errors = []
  131. correct = []
  132. dirs = get_dirs(path = index)
  133. if dirs and dirs != []:
  134. for x, item in enumerate(dirs):
  135. item = unicode(item)
  136. new_name = rename_fomat(item)
  137. if new_name :
  138. correct.append(item)
  139. old_pt = u'%s\\%s'% (index, item)
  140. new_pt = u'%s\\%s'% (index, new_name)
  141. print '[%d]O: %s' % ( x + 1, old_pt)
  142. print '[%d]N: %s' % ( x + 1, new_pt)
  143. else:
  144. errors.append(item)
  145. if errors and errors != []:
  146. print 'Not Match:'
  147. logs({
  148. 'index': index,
  149. 'title': 'Not Match',
  150. 'error_paths': errors,
  151. })
  152. for i, item in enumerate(errors):
  153. print item, '|',
  154. if i % 5 == 4:
  155. print ''
  156. print ''
  157. return correct
  158. #----------------------------------------------------------------------
  159. def manage(index):
  160. """
  161. 程序组织块
  162. """
  163. file_filter = batch_rename_test(index)
  164. do_choice = get_input_result(
  165. word = 'Do with this(y / n)',
  166. choice = ['y', 'n']
  167. )
  168. if do_choice == 'y':
  169. batch_rename(index, dirs= file_filter)
  170. print 'Finished !'
  171. if __name__ == '__main__':
  172. path = WORKING_PATH
  173. manage(index = path)

人气教程排行