python獲取文件后綴名及批量更新目錄下文件后綴名的方法
本文實(shí)例講述了python獲取文件后綴名及批量更新目錄下文件后綴名的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
1. 獲取文件后綴名:
import os
dict = {}
for d, fd, fl in os.walk('/home/ahda/Program/'):
for f in fl:
sufix = os.path.splitext(f)[1][1:]
if dict.has_key(sufix):
dict[sufix] += 1
else:
dict[sufix] = 1
for item in dict.items():
print "%s : %s" % item
這里的關(guān)鍵是os.path.splitext()
如abc/ef.g.h ,這里獲取到的是h
2. python查找遍歷指定文件路徑下指定后綴名的文件實(shí)例:
import sys
import os.path
for dirpath, dirnames, filenames in os.walk(startdir):
for filename in filenames:
if os.path.splitext(filename)[1] == '.txt':
filepath = os.path.join(dirpath, filename)
#print("file:" + filepath)
input_file = open(filepath)
text = input_file.read()
input_file.close()
output_file = open( filepath, 'w')
output_file.write(text)
output_file.close()
3. 批量重命名目錄中的文件后綴實(shí)例:
def swap_extensions(dir, before, after):
if before[:1] != '.': #如果參數(shù)中的后綴名沒有'.'則加上
before = '.' + before
thelen = -len(before)
if after[:1] != '.':
after = '.' + after
for path, subdir, files in os.walk(dir):
for oldfile in files:
if oldfile[thelen:] == before:
oldfile = os.path.join(path, oldfile)
newfile = oldfile[:thelen] + after
os.rename(oldfile, newfile)
print oldfile +' changed to ' + newfile
if __name__ == '__main__':
import sys
if len(sys.argv) != 4:
print 'Usage:swap_extension.py rootdir before after'
sys.exit(1)
swap_extensions(sys.argv[1], sys.argv[2], sys.argv[3])
例子:將e:/py/test目錄下.php結(jié)尾的文件重命名為.py
E:py>python_cook e:/py/test .php .py
e:/py/testtest.php changed to e:/py/testtest.py
e:/py/test1.php changed to e:/py/test1.py
e:/py/test2.php changed to e:/py/test2.py
希望本文所述對大家的Python程序設(shè)計有所幫助。
相關(guān)文章
學(xué)習(xí)Python selenium自動化網(wǎng)頁抓取器
本篇文章給大家介紹了Python selenium自動化網(wǎng)頁抓取器的實(shí)例應(yīng)用以及知識點(diǎn)分析,有需要的參考學(xué)習(xí)下。2018-01-01
python中pandas.DataFrame排除特定行方法示例
這篇文章主要給大家介紹了關(guān)于python中pandas.DataFrame排除特定行的方法,文中給出了詳細(xì)的示例代碼,相信對大家的理解和學(xué)習(xí)具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-03-03
Python使用Selenium實(shí)現(xiàn)瀏覽器打印預(yù)覽功能
在Web開發(fā)中,打印預(yù)覽是一個常見的功能需求,通過打印預(yù)覽,我們可以預(yù)覽和調(diào)整網(wǎng)頁的打印布局、樣式和內(nèi)容,Python的Selenium庫是一個強(qiáng)大的工具,可以自動化瀏覽器操作,包括打印預(yù)覽,本文將介紹如何使用Python Selenium庫來實(shí)現(xiàn)瀏覽器的打印預(yù)覽功能2023-11-11
Python中try用法、內(nèi)置異常類型與自定義異常類型拓展案例詳解
在?Python?里,try?語句主要用于異常處理,其作用是捕獲并處理代碼運(yùn)行期間可能出現(xiàn)的異常,避免程序因異常而意外終止,這篇文章主要介紹了Python中try用法、內(nèi)置異常類型與自定義異常類型拓展,需要的朋友可以參考下2025-04-04
TensorFlow深度學(xué)習(xí)之卷積神經(jīng)網(wǎng)絡(luò)CNN
這篇文章主要介紹了TensorFlow深度學(xué)習(xí)之卷積神經(jīng)網(wǎng)絡(luò)CNN2018-03-03
Python的幾個高級語法概念淺析(lambda表達(dá)式閉包裝飾器)
本文主要記錄自己對幾個高級語法概念的理解:匿名函數(shù)、lambda表達(dá)式、閉包、裝飾器。這幾個概念并非Python特有,但本文只限于用Python做說明2016-05-05

