专栏导读
-
🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手
-
-
-
-
📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅
-
文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏
-
❤️ 欢迎各位佬关注! ❤️
库的介绍
-
在Python中,批量获取文件夹内的文件名并对其进行重命名是一个常见的任务,可以通过使用os模块和pathlib模块来完成。
库的安装
-
os库,内置库,无需安装
-
shutil库,内置库,无需安装
-
pathlib库,内置库,无需安装
方法1:os库—重命名移动版
'''
@Project :测试
@File :测试.py
@IDE :PyCharm
@Author :一晌小贪欢(278865463@qq.com)
@Date :2024/8/11 10:59
'''
import os
folder_path = '文件'
new_folder_path = '新命名'
for filename in os.listdir(folder_path):
old_file = os.path.join(folder_path, filename)
if os.path.isfile(old_file):
new_name = "new_" + filename
new_file = os.path.join(new_folder_path, new_name)
os.system(f"cp{old_file} {new_file}")
print(f"Renamed '{filename}' to '{new_name}'")
方法2:os+shutil—重命名复制版
'''
@Project :测试
@File :测试.py
@IDE :PyCharm
@Author :一晌小贪欢(278865463@qq.com)
@Date :2024/8/11 10:59
'''
import os
import shutil
def copy_files_to_new_folder(folder_path, new_folder_path):
if not os.path.exists(folder_path):
raise FileNotFoundError(f"Folder '{folder_path}' does not exist.")
if not os.path.exists(new_folder_path):
os.makedirs(new_folder_path)
for filename in os.listdir(folder_path):
old_file = os.path.join(folder_path, filename)
if os.path.isfile(old_file):
new_name = "new_" + filename
new_file = os.path.join(new_folder_path, new_name)
if os.path.exists(new_file):
raise FileExistsError(f"File '{new_file}' already exists.")
shutil.copy2(old_file, new_file)
print(f"Copied '{filename}' to '{new_name}'")
folder_path = '文件'
new_folder_path = '新命名'
copy_files_to_new_folder(folder_path, new_folder_path)
方法3:pathlib—重命名移动版
'''
@Project :测试
@File :测试.py
@IDE :PyCharm
@Author :一晌小贪欢(278865463@qq.com)
@Date :2024/8/11 10:59
'''
from pathlib import Path
folder_path = Path('文件')
new_folder_path = Path('新命名')
for file in folder_path.iterdir():
if file.is_file():
new_name = "new_" + file.name
new_file = new_folder_path / new_name
file.rename(new_file)
print(f"Renamed '{file.name}' to '{new_name}'")
方法4:pathlib+shutil—重命名复制版
from pathlib import Path
import shutil
def copy_files_to_new_folder(folder_path, new_folder_path):
if not folder_path.exists():
raise FileNotFoundError(f"Folder '{folder_path}' does not exist.")
if not new_folder_path.exists():
new_folder_path.mkdir(parents=True, exist_ok=True)
for file in folder_path.iterdir():
if file.is_file():
new_name = "new_" + file.name
new_file = new_folder_path / new_name
if new_file.exists():
raise FileExistsError(f"File '{new_file}' already exists.")
shutil.copy2(file, new_file)
print(f"Copied '{file.name}' to '{new_name}'")
folder_path = Path('文件')
new_folder_path = Path('新命名')
copy_files_to_new_folder(folder_path, new_folder_path)
GUI版本附赠
'''
@Project :测试
@File :测试.py
@IDE :PyCharm
@Author :一晌小贪欢(278865463@qq.com)
@Date :2024/8/11 10:59
'''
import os
import shutil
from tkinter import *
from tkinter import filedialog
def copy_files_to_new_folder(folder_path, new_folder_path, prefix="", suffix="", replace_chars=None, add_index=False):
if not os.path.exists(folder_path):
raise FileNotFoundError(f"Folder '{folder_path}' does not exist.")
if not os.path.exists(new_folder_path):
os.makedirs(new_folder_path)
index = 0
for filename in os.listdir(folder_path):
old_file = os.path.join(folder_path, filename)
if os.path.isfile(old_file):
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 add_index:
index += 1
name_only, extension = os.path.splitext(filename)
new_name_base = prefix + name_only + suffix
new_name = f"{index}{new_name_base}{extension}"
new_name = new_name + extension
new_file = os.path.join(new_folder_path, new_name)
shutil.copy2(old_file, new_file)
print(f"Copied '{filename}' to '{new_name}'")
def browse_folder():
folder_path = filedialog.askdirectory()
entry_folder.delete(0, END)
entry_folder.insert(0, folder_path)
def browse_new_folder():
new_folder_path = filedialog.askdirectory()
entry_new_folder.delete(0, END)
entry_new_folder.insert(0, new_folder_path)
def start_copy():
folder_path = entry_folder.get()
new_folder_path = entry_new_folder.get()
prefix = entry_prefix.get()
suffix = entry_suffix.get()
replace_chars = (
entry_old_char.get(), entry_new_char.get()) if entry_old_char.get() and entry_new_char.get() else None
add_index = var_add_index.get()
copy_files_to_new_folder(folder_path, new_folder_path, prefix, suffix, replace_chars, add_index)
root = Tk()
root.geometry('600x200')
root.title("文件重命名—复制版")
Label(root, text="源文件:").grid(row=0, column=0, sticky=W)
entry_folder = Entry(root, width=50)
entry_folder.grid(row=0, column=1)
Button(root, text="浏览", command=browse_folder).grid(row=0, column=2)
Label(root, text="保存文件夹:").grid(row=1, column=0, sticky=W)
entry_new_folder = Entry(root, width=50)
entry_new_folder.grid(row=1, column=1)
Button(root, text="浏览", command=browse_new_folder).grid(row=1, column=2)
Label(root, text="头部添加:").grid(row=2, column=0, sticky=W)
entry_prefix = Entry(root)
entry_prefix.grid(row=2, column=1)
Label(root, text="尾部添加:").grid(row=3, column=0, sticky=W)
entry_suffix = Entry(root)
entry_suffix.grid(row=3, column=1)
Label(root, text="原字符:").grid(row=4, column=0, sticky=W)
entry_old_char = Entry(root, width=5)
entry_old_char.grid(row=4, column=1)
Label(root, text="替换字符").grid(row=4, column=2)
entry_new_char = Entry(root, width=5)
entry_new_char.grid(row=4, column=3)
var_add_index = IntVar()
Checkbutton(root, text="Add index to duplicate names", variable=var_add_index).grid(row=5, columnspan=4, sticky=W)
Button(root, text="Start Copy", command=start_copy).grid(row=6, columnspan=4)
root.mainloop()
总结
-
希望对初学者有帮助
-
致力于办公自动化的小小程序员一枚
-
希望能得到大家的【一个免费关注】!感谢
-
求个 🤞 关注 🤞
-
-
求个 ❤️ 喜欢 ❤️
-
-
求个 👍 收藏 👍
-