python之批量修改檔案名
文章目錄
- python之批量修改檔案名
- 前言
- 一、python批量修改檔案名
- 1.原始碼
- 二、python批量修改檔案名(按順序)
- 1.原始碼
- 三、python批量修改檔案名(洗掉指定字符)
- 1.原始碼
- 四、python批量修改檔案名(按excel給定格式)
- 1.原始碼
- 總結
前言
當我們從網站爬取若干張圖片,或需要將一些txt、excel、jpg等大批量的檔案修改為有規律的名稱,方便整理,
提示:以下是本篇文章正文內容,下面案例可供參考
一、python批量修改檔案名
提示:待修改的檔案夾下只能包含需要修改的檔案,然后更改原始碼里面的路徑即可,
1.原始碼
代碼如下(示例):
#批量修改檔案名
#批量修改圖片檔案名
import os
import re
import sys
def renameall():
fileList = os.listdir(r"E:\py\python3.7\test\test17") #待修改檔案夾
print("修改前:"+str(fileList)) #輸出檔案夾中包含的檔案
currentpath = os.getcwd() #得到行程當前作業目錄
os.chdir(r"E:\py\python3.7\test\test17") #將當前作業目錄修改為待修改檔案夾的位置
num=1 #名稱變數
for fileName in fileList: #遍歷檔案夾中所有檔案
pat=".+\.(jpg|png|gif|py|txt)" #匹配檔案名正則運算式
pattern = re.findall(pat,fileName) #進行匹配
os.rename(fileName,(str(num)+'.'+pattern[0])) #檔案重新命名
num = num+1 #改變編號,繼續下一項
print("---------------------------------------------------")
os.chdir(currentpath) #改回程式運行前的作業目錄
sys.stdin.flush() #重繪
print("修改后:"+str(os.listdir(r"E:\py\python3.7\test\test17"))) #輸出修改后檔案夾中包含的檔案
renameall()
二、python批量修改檔案名(按順序)
1.原始碼
提示:使用os.listdir出現亂序,即修改檔案名的時候不按照檔案排列的順序,例如os.listdir排列的順序是按照例如:1,10,11,2,20,21…的順序,想得到的正常順序:1,2,3,4,5…需進行排序(參考自https://blog.csdn.net/weixin_42575079)
代碼如下(示例):
import os
#設定檔案路徑
path=r'E:\py\python3.7\test\test19\excel'
#獲取該目錄下所有檔案,存入串列中
fileList=os.listdir(path)
#get_key是sotred函式用來比較的元素,該處用lambda運算式替代函式,
get_key = lambda i : int(i.split('.')[0])
new_sort = sorted(fileList, key=get_key)
#print(fileList, '\n', new_sort)
n = 0
for i in fileList:
# 設定舊檔案名(就是路徑+檔案名)
oldname = path + os.sep + new_sort[n] # os.sep添加系統分隔符
# 設定新檔案名
newname = path + os.sep + 'p' + str(n + 1)+'.csv'
os.rename(oldname, newname) # 用os模塊中的rename方法對檔案改名
print(oldname, '======>', newname)
n += 1
三、python批量修改檔案名(洗掉指定字符)
1、批量洗掉指定字符段"-匯總資料-20211123"


2、批量洗掉指定字符段"[ * 圖靈程式設計叢書 * ]."
(參考自https://blog.csdn.net/qiukui111)


1.原始碼
代碼如下(示例):
import os
import re
import time
"""對指定目錄下的所有檔案進行有選擇的修改名稱"""
def ReFileName(dirPath,pattern):
"""
:param dirPath: 檔案夾路徑
:param pattern: 正則匹配模式
:return:
"""
# 對目錄下的檔案進行遍歷
for file in os.listdir(dirPath):
# 判斷是否是檔案
if os.path.isfile(os.path.join(dirPath, file)) == True:
# 用正則匹配,去掉不需要的詞
newName = re.sub(pattern, "", file)
# 設定新檔案名
newFilename = file.replace(file, newName)
# 重命名
os.rename(os.path.join(dirPath, file), os.path.join(dirPath, newFilename))
print("檔案名已統一修改成功")
if __name__ == '__main__':
timeStart = time.time()
dirPath = r"E:\py\python3.7\test\test19\excel1"
# pattern = re.compile(r'\[{1}(.+)]\.')
pattern = re.compile(r'\-匯{1}(.+)3')
ReFileName(dirPath,pattern)
timeEnd = time.time()
print("程式走了%d秒"%(timeEnd-timeStart))
四、python批量修改檔案名(按excel給定格式)
1、批量按照excel姓名和學號匹配修改圖片名稱;



1.原始碼
代碼如下(示例):
import os
import xlwings as wx
def listdir(path, list_name): #傳入存盤的list
for file in os.listdir(path):
# 排除臨時的檔案
if '~$' in file:
continue
# 取得照片清單
if ".jpg" in file:
file_path = os.path.join(path,file)
list_name.append(file_path)
# 取得excel檔案
if ".xlsx" in file:
index_file = os.path.join(path,file)
print("資料源檔案-->"+index_file)
print(list_name)
return index_file
def getinfo(new_name,index_file): # 獲取人員姓名和編號
app = wx.App(visible=False, add_book=False) # 不打開baiexcel
print("讀取人員資訊--->"+index_file)
wb = app.books.open(index_file)
sheet = wb.sheets[0]
nrows = sheet.used_range.last_cell.row #獲取最大行數
ncolumns = sheet.used_range.last_cell.column #獲取最大列數
# 查找姓名和編號的列
file_name = ""
empl_name = ""
empl_numb = ""
ename_col = 0
enumb_col = 0
print("最大列數--->"+str(ncolumns))
for col in range(1, ncolumns+1):
if sheet.range((1,col)).value == "姓名":
ename_col = col
print("姓名的列--->"+str(col))
if sheet.range((1,col)).value == "學號":
enumb_col = col
print("員工號的列--->"+str(col))
# 取行中的姓名和編號
for row in range(2,nrows+1):
empl_name = str(sheet.range((row,ename_col)).value)
empl_numb = str(sheet.range((row,enumb_col)).value)
file_name = (empl_name + empl_numb).split('.')[0] # 新的名字
print(file_name)
new_name.append(file_name)
print(new_name)
wb.close()
app.quit()
def change_name(file_path,new_name,list_name):
# 逐個處理照片
for filename in list_name:
print("舊檔案名"+filename)
old_name = (os.path.basename(filename)).split('.')[0]
# 查找新名字清單中是否有此姓名
for nfile in new_name:
if old_name in nfile:
nfname = file_path+os.sep+nfile+".jpg"
print("新檔案名"+nfname)
os.rename(filename,nfname)
break
def main():
file_path = input('輸入檔案夾路徑:') # 檔案夾位置
try:
#讀取檔案夾下的所有檔案
List_files=[]
index_file = listdir(file_path,List_files)
# 讀取員工姓名和員工號,組成新的檔案名
new_name=[]
getinfo(new_name,index_file)
# 修改檔案名字
change_name(file_path,new_name,List_files)
except Exception as e:
# 列印例外資訊
print(e)
if __name__ == '__main__':
main()
總結
有不對的地方希望大家可以評論留言;
歡迎編程前輩們的幫助,讓大家不再迷路!!
感謝大家的收藏,期待大家的加入,一起學習,一起交流!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/378638.html
標籤:其他
上一篇:影像解析度融合--資料型別
