OS模块--批量修改文件名字(二)
生活随笔
收集整理的這篇文章主要介紹了
OS模块--批量修改文件名字(二)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
通過三個案例,介紹批量修改文件名字的方法。
一、批量在文件前/后任意添加文件名字
二、批量去掉文件字符
三、批量替換某一類型文件名字
一、批量在文件前/后任意添加文件名字(批量在文件前面添加‘方法11’字符)
#在文件前面/后面批量修改文件名字 def filename_modify(target_dir,addstr='end'):#判斷路徑是否存在if os.path.exists(target_dir) == False:raise Exception('path is not exist')#遍歷文件夾中的文件名for file in os.listdir(target_dir):#分割文件名和拓展名filename = os.path.splitext(file)[0]fileExpand = os.path.splitext(file)[1]#不修改文件夾的名字 (方法二:判斷文件名是否為空)if fileExpand == '':continue#將所有文件的后面添加-kkbnewname = filename + addstr + fileExpand#修改名字oldpath = os.path.join(target_dir,file) #老路徑newpath = os.path.join(target_dir,newname) #新路徑os.rename(oldpath,newpath)pass filename_modify('D:\Anaconda',addstr='方法11')二、批量去掉文件字符(批量去掉文件中‘’方法‘’字符)
#批量修改文件名字,將所有文件中的方法11去掉 import re def filename_modify(target_dir,addstr='',position = 'end',oldstr='',newstr=''):#判斷路徑是否存在if os.path.exists(target_dir) == False:raise Exception('path is not exist')#遍歷文件夾中的文件名for file in os.listdir(target_dir):#分割文件名和拓展名filename = os.path.splitext(file)[0]fileExpand = os.path.splitext(file)[1]#不修改文件夾的名字 (方法二:判斷文件名是否為空)if fileExpand == '':continue#判斷添加的位置if position == 'end':#將所有文件的后面添加-kkbnewname = filename + addstr + fileExpandelif position == 'head':#將所有文件的后面添加-kkbnewname = addstr + filename + fileExpandelif position == 'replace':pattern = re.findall(oldstr,filename) #返回列表#列表循環取值for value in pattern: filename = filename.replace(value,newstr)newname = filename + fileExpand#修改名字oldpath = os.path.join(target_dir,file) #老路徑newpath = os.path.join(target_dir,newname) #新路徑os.rename(oldpath,newpath) # print( newname)pass filename_modify('D:\Anaconda',position = 'replace',oldstr = '方法',newstr = '')三、批量替換某一類型文件名字 (批量在xls文件前面添加abc字符)
#批量修改某類文件名字 import redef filename_modify(target_dir,addstr='',position = 'end',oldstr='',newstr='',filetype=None): # target_dir 路徑 ;addstr 添加的字符 ; position 添加的位置 end結尾 head 開頭;oldstr 替換的舊字符 ; #newstr 替換的新字符 ; filetype 指定類型#判斷路徑是否存在if os.path.exists(target_dir) == False:raise Exception('path is not exist')#遍歷文件夾中的文件名for file in os.listdir(target_dir):#分割文件名和拓展名filename = os.path.splitext(file)[0]fileExpand = os.path.splitext(file)[1]#不修改文件夾的名字 (方法二:判斷文件名是否為空)if fileExpand == '':continue#過濾文件類型,從而達到修改指定類型if filetype != None and filetype not in fileExpand:continue#判斷添加的位置if position == 'end':#將所有文件的后面添加newname = filename + addstr + fileExpandelif position == 'head':#將所有文件的后面添加newname = addstr + filename + fileExpandelif position == 'replace':pattern = re.findall(oldstr,filename) #返回列表#列表循環取值for value in pattern: filename = filename.replace(value,newstr)newname = filename + fileExpand#修改名字oldpath = os.path.join(target_dir,file) #老路徑newpath = os.path.join(target_dir,newname) #新路徑os.rename(oldpath,newpath) # print( newname)pass filename_modify('D:\Anaconda',position = 'head',addstr = 'abc',filetype = 'xls')總結
以上是生活随笔為你收集整理的OS模块--批量修改文件名字(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据分析为什么要学Excel
- 下一篇: 【Unity3D—C#】按下任意按键,返