Python自動(dòng)化實(shí)現(xiàn)批量重命名文件
前言
工作中經(jīng)常遇到需要批量處理文件的場(chǎng)景:下載的圖片需要統(tǒng)一命名、報(bào)告需要按日期排序、項(xiàng)目文件需要規(guī)范化……手動(dòng)一個(gè)個(gè)改?太浪費(fèi)時(shí)間了!
今天教你用 Python 幾行代碼搞定批量重命名,從此告別重復(fù)勞動(dòng)。
場(chǎng)景描述
假設(shè)你有一個(gè)文件夾,里面有一堆下載的圖片:
下載文件夾/
├── IMG_20240227_001.jpg
├── IMG_20240227_002.jpg
├── IMG_20240227_003.jpg
└── ...
你想把它們改成更有意義的名稱,比如 項(xiàng)目截圖_001.jpg、項(xiàng)目截圖_002.jpg 這樣。
代碼實(shí)現(xiàn)
import os
def batch_rename(folder_path, prefix):
"""
批量重命名文件
folder_path: 文件夾路徑
prefix: 新文件名前綴
"""
# 獲取文件夾內(nèi)所有文件
files = os.listdir(folder_path)
# 過濾出圖片文件
image_files = [f for f in files if f.endswith(('.jpg', '.png', '.jpeg'))]
# 排序,確保順序一致
image_files.sort()
# 批量重命名
for index, old_name in enumerate(image_files, start=1):
# 獲取文件擴(kuò)展名
ext = os.path.splitext(old_name)[1]
# 生成新文件名
new_name = f"{prefix}_{index:03d}{ext}"
# 構(gòu)建完整路徑
old_path = os.path.join(folder_path, old_name)
new_path = os.path.join(folder_path, new_name)
# 重命名
os.rename(old_path, new_path)
print(f"{old_name} -> {new_name}")
# 使用示例
folder = "/Users/你的用戶名/Downloads/下載文件夾"
batch_rename(folder, "項(xiàng)目截圖")
代碼解析
os.listdir() - 列出文件夾內(nèi)所有文件
os.path.splitext() - 分離文件名和擴(kuò)展名
os.path.join() - 安全地拼接路徑(兼容 Windows 和 Mac)
os.rename() - 執(zhí)行重命名操作
f"{prefix}_{index:03d}" - 格式化字符串,03d 表示 3 位數(shù)字,不足補(bǔ)零
進(jìn)階用法
添加時(shí)間戳
from datetime import datetime
def rename_with_timestamp(folder_path):
files = os.listdir(folder_path)
today = datetime.now().strftime("%Y%m%d")
for index, old_name in enumerate(files, start=1):
ext = os.path.splitext(old_name)[1]
new_name = f"{today}_{index:03d}{ext}"
# ... 重命名代碼
正則表達(dá)式替換
import re
def rename_with_regex(folder_path, pattern, replacement):
"""使用正則替換文件名中的特定內(nèi)容"""
files = os.listdir(folder_path)
for old_name in files:
new_name = re.sub(pattern, replacement, old_name)
if new_name != old_name:
# ... 重命名代碼
注意事項(xiàng)
備份重要文件 - 重命名前最好備份,避免誤操作
測(cè)試小批量 - 先用幾個(gè)文件測(cè)試,確認(rèn)無誤再批量處理
處理沖突 - 如果新文件名已存在,會(huì)報(bào)錯(cuò),需要額外處理
完整安全版本
import os
import shutil
def safe_batch_rename(folder_path, prefix):
files = [f for f in os.listdir(folder_path)
if os.path.isfile(os.path.join(folder_path, f))]
files.sort()
renamed = []
for index, old_name in enumerate(files, start=1):
ext = os.path.splitext(old_name)[1]
new_name = f"{prefix}_{index:03d}{ext}"
old_path = os.path.join(folder_path, old_name)
new_path = os.path.join(folder_path, new_name)
# 避免覆蓋已有文件
if os.path.exists(new_path):
print(f"跳過:{new_name} 已存在")
continue
try:
os.rename(old_path, new_path)
renamed.append((old_name, new_name))
print(f"? {old_name} -> {new_name}")
except Exception as e:
print(f"? {old_name} 失敗: {e}")
print(f"\n完成!共處理 {len(renamed)} 個(gè)文件")
return renamed
總結(jié)
批量重命名只是 Python 自動(dòng)化辦公的入門,掌握了 os 模塊的基礎(chǔ)操作,你就可以:
- 批量移動(dòng)/復(fù)制文件
- 自動(dòng)整理文件夾
- 生成報(bào)告文檔
到此這篇關(guān)于Python自動(dòng)化實(shí)現(xiàn)批量重命名文件的文章就介紹到這了,更多相關(guān)Python批量重命名文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中執(zhí)行MySQL結(jié)果限制和分頁查詢示例詳解
這篇文章主要為大家介紹了Python中執(zhí)行MySQL結(jié)果限制和分頁查詢示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
《Python學(xué)習(xí)手冊(cè)》學(xué)習(xí)總結(jié)
本篇文章是讀者朋友在學(xué)習(xí)了《Python學(xué)習(xí)手冊(cè)》這本書以后,總結(jié)出的學(xué)習(xí)心得,值得大家參考學(xué)習(xí)。2018-01-01
python實(shí)現(xiàn)大學(xué)人員管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)大學(xué)人員管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-10-10
解決Pyinstaller打包為可執(zhí)行文件編碼錯(cuò)誤的問題
這篇文章主要介紹了解決Pyinstaller打包為可執(zhí)行文件編碼錯(cuò)誤的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
pandas數(shù)據(jù)的合并與拼接的實(shí)現(xiàn)
Pandas包的merge、join、concat方法可以完成數(shù)據(jù)的合并和拼接,本文主要介紹了這三種實(shí)現(xiàn)方式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12

