亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Python實(shí)現(xiàn)批量更換指定目錄下文件擴(kuò)展名的方法

Original 2017-01-09 17:46:29 331
abstract:這篇文章主要介紹了Python實(shí)現(xiàn)批量更換指定目錄下文件擴(kuò)展名的方法,結(jié)合完整實(shí)例分析了Python批量修改文件擴(kuò)展名的技巧,并對(duì)比分析了shell命令及scandir的兼容性代碼,需要的朋友可以參考下本文實(shí)例講述了Python實(shí)現(xiàn)批量更換指定目錄下文件擴(kuò)展名的方法。分享給大家供大家參考,具體如下:#encoding=utf-8 #author: walker #date: 2

這篇文章主要介紹了Python實(shí)現(xiàn)批量更換指定目錄下文件擴(kuò)展名的方法,結(jié)合完整實(shí)例分析了Python批量修改文件擴(kuò)展名的技巧,并對(duì)比分析了shell命令及scandir的兼容性代碼,需要的朋友可以參考下

本文實(shí)例講述了Python實(shí)現(xiàn)批量更換指定目錄下文件擴(kuò)展名的方法。分享給大家供大家參考,具體如下:

#encoding=utf-8
#author: walker
#date: 2013-12-06
#function: 深度遍歷指定目錄,更換指定擴(kuò)展名
import os
import os.path
#讀入指定目錄并轉(zhuǎn)換為絕對(duì)路徑
rootdir = raw_input('root dir:\n')
rootdir = os.path.abspath(rootdir)
print('absolute path:\n' + rootdir)
#讀入原擴(kuò)展名并標(biāo)準(zhǔn)化
old_ext = raw_input('old extension:\n')
old_ext = old_ext.strip()
if old_ext[0] != '.':
  old_ext = '.' + old_ext
#讀入新擴(kuò)展名并標(biāo)準(zhǔn)化
new_ext = raw_input('new extension:\n')
new_ext = new_ext.strip()
if new_ext[0] != '.':
  new_ext = '.' + new_ext
for parent, dirnames, filenames in os.walk(rootdir):
  for filename in filenames:
    pathfile = os.path.join(parent, filename)
    if pathfile.endswith(old_ext):
      new_pathfile = os.path.splitext(pathfile)[0] + new_ext
      print('=======================================================')
      print(pathfile)
      print('-------------------------------------------------------')
      print(new_pathfile)
      print('=======================================================')
      os.rename(pathfile, new_pathfile)

PS:上述功能一個(gè)shell命令也可以實(shí)現(xiàn)

#將后綴.ini換成.txt
#路徑名可以是相對(duì)路徑或絕對(duì)路徑
find 路徑名 | rename 's/\.ini$/\.txt/'

注意,上面的rename命令是perl版的rename命令。

PS2:scandir的兼容代碼。

# Use the built-in version of scandir/walk if possible, otherwise
# use the scandir module version
try:
  from os import scandir, walk  #python3.5+
except ImportError:
  from scandir import scandir, walk #python3.4-

更多關(guān)于Python實(shí)現(xiàn)批量更換指定目錄下文件擴(kuò)展名的方法請(qǐng)關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!

Release Notes

Popular Entries