python批處理修改檔案的名字
【十一月的蕭邦】
蛋蛋說我寫的部落格叫做情感部落格,所以現在不忍心,出來水一篇,畢竟為了慶祝十一月的到來。
十一月有周杰倫的新專輯,當時我們買了藏在書包裡,開運動會,一本漫畫,一副耳機,躺在綠油油的草地上,哎,小姐,請問有沒有賣半島鐵盒,走廊燈關上,恩恩聽不清,我走到窗邊書包放。。。。
感覺這些就是整個世界。
這個其實叫做寫在前面的話,因為現在是十一月的第一天,小時候超級喜歡十一月,因為每個運動會都會開在十一月,然後昆明的十一月的氣候超級好,天空很藍,空氣微微冷。每次開運動會都可以偷偷跑出學校門口買好吃的。小夥伴會把自己家的狗狗帶到學校,spirit我還記得她的狗狗叫做這個名字。
小時候我可是運動健將,因為沒有人的仰臥起坐能夠比過我,跳遠也很厲害,然後每次都可以拿獎。但是拿獎的時候總是很尷尬,因為我的名字很少見,主持人喜歡把我的名字分開念,生氣。我還記得楊龍當時笑的嘴都快裂開了。大家全部笑的趴在地上,生氣!!!
哈哈,好的開始寫技術部分,今天的內容叫做批處理修改檔案的名字。當然我們是不可能講這麼簡單的東西的,只是通過這個簡單的東西我們講怎麼一點點的改進自己的程式碼,實現程式碼的高效複用,也就是傳說中的造輪子。把自己的程式碼改造的更加的完備。更加的實用,寫一些值得收藏的程式碼。
1.運用場景
假設我們有一批檔案經過某些加工之後名字變了,但是我們想按照自己的意願改名字,在Python中給我們提供了一個強大的輪子,叫做os.rename(oldname,newname)
通過呼叫這個函式呢,我們可以輕易的實現改名字。
為了更加形象的說明我們的問題,我們來看幾張圖片吧。
比如說在某個資料夾的下面我們存在著一些檔案,就像上面這張圖片一樣,在-前面的是我們檔案本來的名字,經過了某些處理之後我們的檔案變成了上面的這個樣子,我們只想保留檔案原來的名字,就像下面這張圖一樣。這個時候我們就需要做一個批處理,來修改我們這些檔案的名字。
使得它們變成上面的這個樣子。
2.實現思路
根據需要的需求,我們可以設計出我們的實現思路。
1.我們發現我們只要“-”這個符號前面的檔名,之後在加上檔案的檔案型別,字尾,那麼就是我們檔案最終的名字。
2.我們知道檔案的名字其實是字串,在字串中我們可以根據split() 這個函式來進行分割,我們根據split("-")
這個函式得到的是一個List,我們只需要去List的第一個元素就是我們檔名,之後加上字尾,然後使用我們Python自帶的函式,我們就可以實現檔名的重新命名。
3.其實我之前寫過一個類似的功能,就是從APK中提取出我們的classes.dex檔案和我們的so檔案
那個難度比這個大一點。我們用到了zip檔案的讀取和寫入,當然還有其他的實現思路。
3.程式碼實現
講完了我們的運用場景,實現思路,是不是覺得我們的程式碼實現會比較簡單呢。OK,那麼我們就來寫一個簡單的程式碼。
我們先來實現一下一個比較簡單的版本:
程式碼複製版本:
#!/usr/bin/env python
# coding=utf-8
# @author : Chicho
# @version : 1.0
# @date : 2016-11-1 11:00
# @ function : Batching rename the name of file
# @running : python renameGator.py
import os
#path儲藏了我們需要處理檔案的路徑,假設我的路徑就叫這個
path = "/home/chicho/test/Out/"
# 之後我們或許檔案列表使用的是listdir()這個函式,我們需要
#引入 os --->import os 才能使用
# 下面的圖形為我們展示了這個函式的執行結果
fileList=os.listdir(path)
for f in fileList:
filePath = os.path.join(path,f)
# 根據緊接著的圖片我們可以發現,裡面含有資料夾,還有檔案,我們
#需要處理的只是檔案,不是資料夾
#所以我們需要isfile來判斷一下
if os.path.isfile(filePath):
portion = f.split("-")[0]# 獲取檔名的前半部分
#加上字尾
newName = portion + ".xml"
#新檔案的路徑
#如果程式碼和檔案不在同一個目錄下必須這麼修改
#否則生成的檔案就會在裡程式碼執行的目錄下面
newNamePath=os.path.join(path,newName)
#重新命名
os.rename(filePath,newNamePath)
print "new we are handleding the {0}".format(newName)
print "all work is done!"
OK,我們 就這麼搞定了我們的程式碼。
3.1 程式碼升級
當然了,這種是屬於輪子型的程式碼,我們需要在擴充套件一下,讓它能夠更加的智慧。比如說路徑先不要固定死,我們可以自己輸入。下面我們再來個升級版本。
我們在執行的時候就直接把引數傳給我們的程式,也就是我們需要處理的路徑
#!/usr/bin/env python
# coding=utf-8
# @author : Chicho
# @version : 2.0
# @date : 2016-11-1 11:00
# @ function : Batching rename the name of file
# @running : python renameGator.py
# @running : python renameGator.py you_file_path
# : e.g: python renameGator.py /home/chicho/test/Out/
import os
import sys
def Usage():
print "usage:"
print "python renameGator.py your_file_path\n"
if len(sys.argv)==1:
path = "/home/chicho/test/sootAndroidOut/"
elif len(sys.argv)==2:
path = sys.argv[1]
if not os.path.exists(path):
print "\nyou input is wrong, cannot find the path!"
print "Please check you path!\n"
Usage()
sys.exit(1)
fileList=os.listdir(path)
for f in fileList:
filePath = os.path.join(path,f)
if os.path.isfile(filePath):
portion = f.split("-")[0]
newName = portion + ".xml"
newNamePath=os.path.join(path,newName)
os.rename(filePath,newNamePath)
print "new we are handleding the ****++ {0} ++****".format(newName)
print "all work is done!"
當然了這個只是一個簡答 的Demo,還有不完善的地方,就比如說我們引數處理部分還是不完善。還需要再增加一個判斷條件,防止使用者的錯誤輸入。
下面我們再把逼格提升一點。寫的更加像程式設計師該做的事情。
#!/usr/bin/env python
# coding=utf-8
# @author : Chicho
# @version : 3.0
# @date : 2016-11-1 11:00
# @ function : Batching rename the name of file
# @running : python renameGator.py
# @running : python renameGator.py you_file_path
# : e.g: python renameGator2.py /home/chicho/test/sootAndroidOut/
# @running : python renameGator2.py -h
# @running : python renameGator2.py -i your_file_path
# e.g: python renameGator2.py /home/chicho/test/sootAndroidOut/
import os
import sys,getopt
def Usage():
print "usage:"
print "python renameGator.py your_file_path\n"
def usage1():
print "usage:"
print "python renameGator2.py -i your_file_path"
#********************************
opts,args = getopt.getopt(sys.argv[1:],"hi:")
for op,value in opts:
if op == "-i":
path = value
if not os.path.exists(path):
print "Cannot find the Path!"
sys.exit(1)
elif op == "-h":
usage1()
sys.exit(0)
if len(sys.argv)==1:
path = "/home/chicho/test/sootAndroidOut/"
elif len(sys.argv)==2:
path = sys.argv[1]
if not os.path.exists(path):
print "\nyou input is wrong, cannot find the path!"
print "Please check you path!\n"
Usage()
print "or"
usage1()
sys.exit(1)
fileList=os.listdir(path)
i=0
for f in fileList:
filePath = os.path.join(path,f)
if os.path.isfile(filePath):
portion = f.split("-")[0]
newName = portion + ".xml"
newNamePath=os.path.join(path,newName)
os.rename(filePath,newNamePath)
print "new we are handleding the ****++ {0} ++****".format(newName)
i = i+1
print "There are {0} files being handled!".format(i)
print "all work is done!"
使用者在不知道怎麼執行程式碼的情況下我們可以通過執行 -h來得到幫助。
但是這程式碼的容錯能力還是一般,要是有的檔案當中根本就沒有“-”,那麼我們就只需要修改需要改名字的檔案。
比如上面這個我們不需要處理apv.xml這個檔案
如果要用上面這個程式碼我們發現處理的結果就會有問題。
所以我們再來改進一下我們的程式碼
#!/usr/bin/env python
# coding=utf-8
# @author : Chicho
# @version : 4.0
# @date : 2016-11-1 11:00
# @ function : Batching rename the name of file
# @running : python renameGator.py
# @running : python renameGator.py you_file_path
# : e.g: python renameGator3.py /home/chicho/test/sootAndroidOut/
# @running : python renameGator3.py -h
# @running : python renameGator3.py -i your_file_path
# e.g: python renameGator2.py /home/chicho/test/sootAndroidOut/
import os
import sys,getopt
def Usage():
print "usage:"
print "python renameGator.py your_file_path\n"
def usage1():
print "usage:"
print "python renameGator2.py -i your_file_path"
#********************************
opts,args = getopt.getopt(sys.argv[1:],"hi:")
for op,value in opts:
if op == "-i":
path = value
if not os.path.exists(path):
print "Cannot find the Path!"
sys.exit(1)
elif op == "-h":
usage1()
sys.exit(0)
if len(sys.argv)==1:
path = "/home/chicho/test/sootAndroidOut/"
elif len(sys.argv)==2:
path = sys.argv[1]
if not os.path.exists(path):
print "\nyou input is wrong, cannot find the path!"
print "Please check you path!\n"
Usage()
print "or"
usage1()
sys.exit(1)
fileList=os.listdir(path)
i=0
for f in fileList:
filePath = os.path.join(path,f)
if os.path.isfile(filePath):
if not "-" in f:
continue
portion = f.split("-")[0]
newName = portion + ".xml"
newNamePath=os.path.join(path,newName)
os.rename(filePath,newNamePath)
print "new we are handleding the ****++ {0} ++****".format(newName)
i = i+1
print "There are {0} files being handled!".format(i)
print "all work is done!"
執行一下看看處理的結果
當然了,這個是個輪子的程式碼,為了能方便廣大人民也能使用這個程式碼,我們就把這個程式碼改裝成輪子。
我們把這個程式碼寫入到一個叫做rename.py 的程式碼中,改造成輪子。
#!/usr/bin/env python
# coding=utf-8
# @author : Chicho
# @version : 1.0
# @date : 2016-11-1 11:00
# @ function : Batching rename the name of file
# @running : python rename.py
import os
def renameFile(path):
fileList=os.listdir(path)
for f in fileList:
filePath = os.path.join(path,f)
if os.path.isfile(filePath):
portion = f.split("-")[0]
newName = portion + ".xml"
newNamePath=os.path.join(path,newName)
os.rename(filePath,newNamePath)
print "new we are handleding the {0}".format(newName)
print "all work is done!"
怎麼呼叫呢,
看下面的程式碼:
#!/usr/bin/env python
# coding=utf-8
# @author : Chicho
# @version : 1.0
# @date : 2016-11-1 13:45
# @function : Batching rename the name of files
# @running : python invoke.py
import rename
path="/home/chicho/test/sootAndroidOut/"
#rename.renameFile(path)
if __name__== "__main__":
rename.renameFile(path)
那麼,我們就把整個功能都實現了。
寫在後面的話
好好學習,天天向上
你必須非常努力,才可以看起來毫不費力
不要忘了做過的夢
shining,shinging
每當有淚兒流
就回到那個宇宙
天上星星,彷彿聽她訴說
驕傲的閃不停
相關推薦
python批處理修改檔案的名字
【十一月的蕭邦】 蛋蛋說我寫的部落格叫做情感部落格,所以現在不忍心,出來水一篇,畢竟為了慶祝十一月的到來。 十一月有周杰倫的新專輯,當時我們買了藏在書包裡,開運動會,一本漫畫,一副耳機,躺在綠油油的草地上,哎,小姐,請問有沒有賣半島鐵盒,走廊燈關上,恩恩聽不
Python批處理修改檔案字尾名
需求:為了寫OJ自動掛題 在這樣的情況下: 1.OJ掛題的需求要求所有的樣例檔案必須要以.in .out形式出現 (原本的資料形式是.txt) 2.並且要把所有的樣例都壓縮到一個壓縮包裡 3.既然支援一件處理檔案 那麼也要處理子目錄下的檔案 更新1:還要過濾掉inpu
bat 批處理修改host檔案
在測試的時候,經常會遇到修改host 的情況,每次都開啟host手動新增,很繁瑣地,怎麼寫個批處理檔案,雙擊下就把host修改了呢,請看下面程式碼: @echo off color 0F @attrib -r "%windir%\system32\drivers\
Python指令碼批處理JSON檔案,去除製表符、空格、回車等多餘符號
root_dir_path = "E:\popstar3\Popstar3_3.x_0_small\Resources\ui" extern_name_list = [".json", ".ExportJson"] import os import
批處理修改IP
code 處理 ins erro 自動 style 子網 ask error 由於公司網絡是固定IP,家裏網絡是自動獲取,每次更換太麻煩,百度查到批處理修改IP,復制到此處 1.新建ip.txt 2. set /p choice=1固定ip,2自動獲取: echo.
懶人的小技巧, 批處理修改IP
ets itl ase 工作 ... rep ora blog else 相信很多人都有這樣的麻煩, 工作單位的IP網段與住的不一致, 自己的筆記本在單位和回家的時候每次都要更改IP, 很麻煩, 偷個懶, 做了個批處理來修改IP,方便一點. 還有就是可以把工作的時候才需要
bat 批處理修改多層文件夾名稱
結果 led bsp 簡潔 dexp 通過 ech info 修改名稱 最近朋友一直抱怨說有一堆的文件夾需要重新修改名稱,一個一個處理非常浪費時間,問有沒有什麽簡潔的方法進行處理。 在明白了朋友的需求後,想到可以寫個bat批處理文件進行處理。 首先分析下朋友的需求: 原文件
bat批處理開啟檔案路徑或者程式
PEM開啟程式 @echo off start /min "" "D:\Program Files\Xshell\Xshell.exe" PEM設定延時時間 timeout /t 10 start /min "" "D:\Program Files\SecureCRT\SecureCRT
BAT批處理提取檔案內容替換指定檔案內容
從test.txt裡查詢CLIENT_HOME 按=分割,獲取值 替換1.txt裡的所有CKIENT_HOME 由於修改的檔案是xml,所以需要chcp 65001切換編碼到utf8,否則會出現中文亂碼 批處理bat: adding: 0px; font-fam
windows下java專案打包、啟動批處理 .bat檔案
maven打包,指令碼內容: @echo off echo 正在設定臨時環境變數 set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_45 set MAVEN_HOME=D:\apache-maven-3.2.5 set CLASSPATH=.;%JAVA_HO
批處理解決檔案移動問題
學習hibernate的時候檔案結構是這樣的。 這是所有視訊所在的資料夾,視訊在資料夾裡面,就像這樣: 這樣的檔案結構有一個缺點,看起來不爽,怎麼不爽呢?每次看完一個視訊的時候不會自動播放下一個,還得回到上一級目錄,點選下一集視訊才可以播放,簡直費時費力。 最近公司裡面打包
windows批處理修改IE主頁
@echo off >nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system" if '%errorlevel%' NEQ '0' ( ec
Python Djiang xadmin修改檔案/圖片時刪除舊檔案/圖片
Python Djiang xadmin修改檔案/圖片時刪除舊檔案/圖片 ✎ 使用signals的pre_save,在資料儲存前執行相關操作。 #在對應的models.py中 class banner(models.Model): ... fro
Windows 批處理修改hosts指令碼
方便修改hosts檔案和加入商家域名,可以儲存.bat指令碼或者打包成.exe執行程式 @echo off @echo ###################################################### echo
BAT批處理修改MSDOS視窗標題、大小、字型及背景顏色
通過批處理Bat,可修改MSDOS視窗標題、大小、字型及背景顏色等,下面逐一為你介紹。 下面的方法,可在MSDOS視窗中直接使用程式碼,也可以將程式碼寫入BAT檔案中使用。 ①改變視窗大小 mode con cols=30 lines=20 ②設定cmd視窗的標題
DOS 批處理獲取檔案大小
最近研究了幾天,終於寫了出來.特別分享. @echo off&setlocal enabledelayedexpansion set "fn=E:\cheleon\data\localdb.mdb"set /a "k=0"for /f "skip=4 delims=
bat批處理刪除檔案
最近接觸到了一些有意思的技術,比如chrome外掛,批處理指令碼。以前都只會用,現在想著有機會能做一個。 剛好最近在做一個功能,匯入檔案,上傳過程中要校驗資料,如果失敗的話可以下載錯誤報告到本地。不過錯誤報告會堆積在資料夾下,看著挺礙眼,每次都要手動刪除挺麻煩
批處理 修改登錄檔 禁用USB
需要禁用本機USB介面。可通過修改登錄檔來實現,最簡單的方式就是用批處理執行。 首先 HKLM\SYSTEM\CurrentControlSet\services\USBSTOR 下Start值該為4後,USB裝置不可使用。下面就用兩種簡單惡批處理來實現修改登錄
Cmd批處理替換檔案
語法: copy source [destination] 引數: source 指定要被複制的檔案的位置和名稱。Source 可由驅動器號和冒號、目錄名、檔名或組合所
Python批處理更改檔名os.rename
在工作中,我們經常會遇到需要對大批量檔案進行重新命名的操作,而python提供了很簡單的方法: import os #top是目標資料夾(絕對路徑),os.walk會讀取其內的檔案及資料夾直至空。