Python 批量修改檔案名稱的3種實現方法

來源:互聯網
上載者:User

例子一

 代碼如下 複製代碼

python 批量修改檔案名稱代碼
view plaincopy to clipboardprint?
#!/usr/bin/env python 
#coding=utf-8 
import os,os.path 
import shutil,string 
dir = C:\test
for i in os.listdir(dir): 
    newfile = i.replace(.,_) 
    oldfullfile = dir \ i 
    newfullfile = dir \ newfile 
    print oldfullfile 
    print newfullfile 
    shutil.move(oldfullfile,newfullfile) 
    print i 


例子二,

 代碼如下 複製代碼

import sys, string, os, shutil
#輸入目錄名和首碼名,重新命名後的名稱結構類似prefix_0001
def RenameFiles(srcdir, prefix):
    srcfiles = os.listdir(srcdir)
    index = 1
    for srcfile in srcfiles:
        srcfilename = os.path.splitext(srcfile)[0][1:]
        sufix = os.path.splitext(srcfile)[1]
  #根據目錄下具體的檔案數修改%號後的值,"%04d"最多支援9999
        destfile = srcdir + "//" + prefix + "_%04d"%(index) + sufix
        srcfile = os.path.join(srcdir, srcfile)
        os.rename(srcfile, destfile)
        index += 1
srcdir = "D://Music"
prefix = "IMG_2011"
RenameFiles(srcdir, prefix)

例子三,非常完美的解決方案

一段 Python 批量修改檔案名稱的代碼分享給大家;

 代碼如下 複製代碼

#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):
  """
  錯誤記錄
  """
  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):
  """
  擷取正確的輸入結果
  """
  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):
  """
  測試
  返回過濾結果
  """
  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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.