Python實(shí)現(xiàn)批量獲取文件夾內(nèi)文件名并重命名
1、背景介紹
有時(shí)候我們經(jīng)常需要將批量的文件進(jìn)行重命名,比如:
- ① 批量在文件名【前面】加上 自定義字符
- ② 批量在文件名【后面】加上 自定義字符
- ③ 批量在【替換】文件名中的字符
- ④ 批量去除 空格
- ⑤ 結(jié)果可以選擇復(fù)制文件 或者 移動(dòng) 文件
2、庫(kù)的安裝
| 庫(kù) | 用途 | 安裝 |
|---|---|---|
| PyQt5 | 界面設(shè)計(jì) | pip install PyQt5 -i https://pypi.tuna.tsinghua.edu.cn/simple/ |
| shutil | 文件移動(dòng) | 內(nèi)置庫(kù)無(wú)需安裝 |
| os | 文件移動(dòng) | 內(nèi)置庫(kù)無(wú)需安裝 |
3、核心代碼
復(fù)制 或 移動(dòng)
shutil.move(old_file, new_file) # 移動(dòng)文件 shutil.copy2(old_file, new_file) # 復(fù)制文件
4、完整代碼
# -*- coding: UTF-8 -*-
'''
@Project :測(cè)試
@File :文件重命名.py
@IDE :PyCharm
@Author :一晌小貪歡(278865463@qq.com)
@Date :2025/2/7 下午8:02
'''
import os
import shutil
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QVBoxLayout, QHBoxLayout, QPushButton, QFileDialog, QCheckBox, QFormLayout, QSpinBox, QGroupBox, QDialogButtonBox, QRadioButton, QButtonGroup
def copy_or_move_files(folder_path, new_folder_path, prefix="", suffix="", replace_chars=None, add_index=False, remove_spaces=False, move_files=False):
# 檢查源文件夾是否存在
if not os.path.exists(folder_path):
raise FileNotFoundError(f"Folder '{folder_path}' does not exist.")
# 檢查目標(biāo)文件夾是否存在,不存在則創(chuàng)建
if not os.path.exists(new_folder_path):
os.makedirs(new_folder_path)
index = 0
# 遍歷文件夾內(nèi)所有文件
for filename in os.listdir(folder_path):
# 構(gòu)造完整文件路徑
old_file = os.path.join(folder_path, filename)
# 判斷是否為文件(排除文件夾)
if os.path.isfile(old_file):
# 分割文件名和擴(kuò)展名
name_only, extension = os.path.splitext(filename)
# 生成新文件名
new_name = name_only
if prefix:
new_name = prefix + new_name
if suffix:
new_name = new_name + suffix
if replace_chars:
old_char, new_char = replace_chars
new_name = new_name.replace(old_char, new_char)
if remove_spaces:
new_name = new_name.replace(" ", "") # 去除空格
if add_index:
index += 1
name_only, extension = os.path.splitext(filename) # 分離原始文件名和擴(kuò)展名
new_name_base = prefix + name_only + suffix # 生成基礎(chǔ)的新文件名
new_name = f"{index}{new_name_base}{extension}" # 在文件名最前面添加索引
# 重新組合文件名和擴(kuò)展名
new_name = new_name + extension
new_file = os.path.join(new_folder_path, new_name)
# 根據(jù)用戶(hù)選擇執(zhí)行復(fù)制或移動(dòng)操作
if move_files:
shutil.move(old_file, new_file) # 移動(dòng)文件
print(f"Moved '{filename}' to '{new_name}'")
else:
shutil.copy2(old_file, new_file) # 復(fù)制文件
print(f"Copied '{filename}' to '{new_name}'")
class FileCopyApp(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("文件重命名—復(fù)制版")
self.setGeometry(900, 500, 600, 300)
# Initialize UI components
self.init_ui()
def init_ui(self):
# Create layout
layout = QVBoxLayout()
# Source Folder
self.folder_label = QLabel("源文件:")
self.folder_line_edit = QLineEdit()
self.browse_button = QPushButton("瀏覽")
self.browse_button.clicked.connect(self.browse_folder)
# Destination Folder
self.new_folder_label = QLabel("保存文件夾:")
self.new_folder_line_edit = QLineEdit()
self.new_folder_button = QPushButton("瀏覽")
self.new_folder_button.clicked.connect(self.browse_new_folder)
# Prefix, Suffix, Char Replacement
self.prefix_label = QLabel("頭部添加:")
self.prefix_line_edit = QLineEdit()
self.suffix_label = QLabel("尾部添加:")
self.suffix_line_edit = QLineEdit()
self.old_char_label = QLabel("原字符:")
self.old_char_line_edit = QLineEdit()
self.new_char_label = QLabel("替換字符:")
self.new_char_line_edit = QLineEdit()
# Index and Space Removal
self.add_index_check_box = QCheckBox("重復(fù)名稱(chēng)添加索引")
self.remove_spaces_check_box = QCheckBox("去除文件名中的空格")
# Copy or Move Radio Buttons
self.copy_radio = QRadioButton("復(fù)制")
self.move_radio = QRadioButton("移動(dòng)")
self.copy_radio.setChecked(True) # 默認(rèn)選擇復(fù)制
self.action_group = QButtonGroup()
self.action_group.addButton(self.copy_radio)
self.action_group.addButton(self.move_radio)
# Start Button
self.start_button = QPushButton("開(kāi)始")
self.start_button.clicked.connect(self.start_copy_or_move)
# Arrange components
folder_layout = QHBoxLayout()
folder_layout.addWidget(self.folder_label)
folder_layout.addWidget(self.folder_line_edit)
folder_layout.addWidget(self.browse_button)
new_folder_layout = QHBoxLayout()
new_folder_layout.addWidget(self.new_folder_label)
new_folder_layout.addWidget(self.new_folder_line_edit)
new_folder_layout.addWidget(self.new_folder_button)
replace_layout = QFormLayout()
replace_layout.addRow(self.prefix_label, self.prefix_line_edit)
replace_layout.addRow(self.suffix_label, self.suffix_line_edit)
replace_layout.addRow(self.old_char_label, self.old_char_line_edit)
replace_layout.addRow(self.new_char_label, self.new_char_line_edit)
options_layout = QVBoxLayout()
options_layout.addWidget(self.add_index_check_box)
options_layout.addWidget(self.remove_spaces_check_box)
# Copy or Move Layout
action_layout = QHBoxLayout()
action_layout.addWidget(self.copy_radio)
action_layout.addWidget(self.move_radio)
# Layout adjustments
layout.addLayout(folder_layout)
layout.addLayout(new_folder_layout)
layout.addLayout(replace_layout)
layout.addLayout(options_layout)
layout.addLayout(action_layout)
layout.addWidget(self.start_button)
# Set main layout
self.setLayout(layout)
def browse_folder(self):
folder_path = QFileDialog.getExistingDirectory(self, "選擇源文件夾")
if folder_path:
self.folder_line_edit.setText(folder_path)
def browse_new_folder(self):
new_folder_path = QFileDialog.getExistingDirectory(self, "選擇保存文件夾")
if new_folder_path:
self.new_folder_line_edit.setText(new_folder_path)
def start_copy_or_move(self):
folder_path = self.folder_line_edit.text()
new_folder_path = self.new_folder_line_edit.text()
prefix = self.prefix_line_edit.text()
suffix = self.suffix_line_edit.text()
replace_chars = (
self.old_char_line_edit.text(), self.new_char_line_edit.text()) if self.old_char_line_edit.text() and self.new_char_line_edit.text() else None
add_index = self.add_index_check_box.isChecked()
remove_spaces = self.remove_spaces_check_box.isChecked()
move_files = self.move_radio.isChecked() # 判斷用戶(hù)選擇的是復(fù)制還是移動(dòng)
copy_or_move_files(folder_path, new_folder_path, prefix, suffix, replace_chars, add_index, remove_spaces, move_files)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = FileCopyApp()
window.show()
sys.exit(app.exec_())
5、效果圖

到此這篇關(guān)于Python實(shí)現(xiàn)批量獲取文件夾內(nèi)文件名并重命名的文章就介紹到這了,更多相關(guān)Python文件重命名內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
嘗試使用Python多線(xiàn)程抓取代理服務(wù)器IP地址的示例
這篇文章主要介紹了嘗試使用Python多線(xiàn)程抓取代理服務(wù)器IP地址的示例,盡管有GIL的存在使得Python并不能真正實(shí)現(xiàn)多線(xiàn)程并行,需要的朋友可以參考下2015-11-11
解決pip安裝第三方庫(kù),但PyCharm中卻無(wú)法識(shí)別的問(wèn)題for mac
這篇文章主要介紹了解決pip安裝第三方庫(kù),但PyCharm中卻無(wú)法識(shí)別的問(wèn)題for mac,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-09-09
python開(kāi)發(fā)中module模塊用法實(shí)例分析
這篇文章主要介紹了python開(kāi)發(fā)中module模塊用法,以實(shí)例形式較為詳細(xì)的分析了Python中模塊的功能、定義及相關(guān)使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
Python中l(wèi)en()函數(shù)用法使用示例
這篇文章主要介紹了Python中的len()函數(shù),包括其基礎(chǔ)用法、適用范圍、常見(jiàn)使用場(chǎng)景以及在第三方庫(kù)(如NumPy和pandas)中的應(yīng)用,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2025-03-03
tensorflow 實(shí)現(xiàn)數(shù)據(jù)類(lèi)型轉(zhuǎn)換
今天小編就為大家分享一篇tensorflow 實(shí)現(xiàn)數(shù)據(jù)類(lèi)型轉(zhuǎn)換,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
使用Python實(shí)現(xiàn)下載網(wǎng)易云音樂(lè)的高清MV
本文給大家分享的是一則使用Python實(shí)現(xiàn)下載網(wǎng)易云音樂(lè)中高清MV的代碼,本人新手,沒(méi)有做特別的功能,僅僅是直接循環(huán)了MV的id,小伙伴們可以自己擴(kuò)展下。2015-03-03
使用PyInstaller將Python程序文件轉(zhuǎn)換為可執(zhí)行程序文件
與py2exe一樣,PyInstaller程序也可以將Python的.py程序文件轉(zhuǎn)換為.exe,并且還有Linux的版本,下面我們就來(lái)詳細(xì)看一下如何使用PyInstaller將Python程序文件轉(zhuǎn)換為可執(zhí)行程序文件2016-07-07

