python批量修改文件名的三種方法實例
前言
當我們從網(wǎng)站爬取若干張圖片,或需要將一些txt、excel、jpg等大批量的文件修改為有規(guī)律的名稱,方便整理。
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、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 #改變編號,繼續(xù)下一項
print("---------------------------------------------------")
os.chdir(currentpath) #改回程序運行前的工作目錄
sys.stdin.flush() #刷新
print("修改后:"+str(os.listdir(r"E:\py\python3.7\test\test17"))) #輸出修改后文件夾中包含的文件
renameall()
二、python批量修改文件名(按順序)
1.源碼
提示:使用os.listdir出現(xiàn)亂序,即修改文件名的時候不按照文件排列的順序,例如os.listdir排列的順序是按照例如:1,10,11,2,20,21…的順序,想得到的正常順序:1,2,3,4,5…需進行排序(參考自http://www.dbjr.com.cn/article/247381.htm)
代碼如下(示例):
import os
#設(shè)定文件路徑
path=r'E:\py\python3.7\test\test19\excel'
#獲取該目錄下所有文件,存入列表中
fileList=os.listdir(path)
#get_key是sotred函數(shù)用來比較的元素,該處用lambda表達式替代函數(shù)。
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:
# 設(shè)置舊文件名(就是路徑+文件名)
oldname = path + os.sep + new_sort[n] # os.sep添加系統(tǒng)分隔符
# 設(shè)置新文件名
newname = path + os.sep + 'p' + str(n + 1)+'.csv'
os.rename(oldname, newname) # 用os模塊中的rename方法對文件改名
print(oldname, '======>', newname)
n += 1
三、python批量修改文件名(刪除指定字符)
1、批量刪除指定字符段"-匯總數(shù)據(jù)-20211123"


2、批量刪除指定字符段"[ * 圖靈程序設(shè)計叢書 * ]."
(參考自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)
# 設(shè)置新文件名
newFilename = file.replace(file, newName)
# 重命名
os.rename(os.path.join(dirPath, file), os.path.join(dirPath, newFilename))
print("文件名已統(tǒng)一修改成功")
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("數(shù)據(jù)源文件-->"+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 #獲取最大行數(shù)
ncolumns = sheet.used_range.last_cell.column #獲取最大列數(shù)
# 查找姓名和編號的列
file_name = ""
empl_name = ""
empl_numb = ""
ename_col = 0
enumb_col = 0
print("最大列數(shù)--->"+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()
總結(jié)
到此這篇關(guān)于python批量修改文件名的三種方法的文章就介紹到這了,更多相關(guān)python批量修改文件名內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Python list 與 NumPy.ndarry 切片之間的對比
這篇文章主要介紹了詳解Python list 與 NumPy.ndarry 切片之間的區(qū)別的相關(guān)資料,list 切片返回的是不原數(shù)據(jù),對新數(shù)據(jù)的修改不會影響原數(shù)據(jù)而NumPy.ndarry 的切片返回的是原數(shù)據(jù)需要的朋友可以參考下2017-07-07
pycharm from lxml import etree標紅問題及解決
這篇文章主要介紹了pycharm from lxml import etree標紅問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01

