Python—批量获取文件夹内文件名及重命名文件教程(附赠GUI版本)

专栏导读

  • 🌸 欢迎来到Python办公自动化专栏—Python处理办公问题,解放您的双手

  • 🏳️‍🌈 博客主页:请点击——> 一晌小贪欢的博客主页求关注

  • 👍 该系列文章专栏:请点击——>Python办公自动化专栏求订阅

  • 🕷 此外还有爬虫专栏:请点击——>Python爬虫基础专栏求订阅

  • 📕 此外还有python基础专栏:请点击——>Python基础学习专栏求订阅

  • 文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏

  • ❤️ 欢迎各位佬关注! ❤️

库的介绍

  • 在Python中,批量获取文件夹内的文件名并对其进行重命名是一个常见的任务,可以通过使用os模块和pathlib模块来完成。

库的安装

  • os库,内置库,无需安装

  • shutil库,内置库,无需安装

  • pathlib库,内置库,无需安装

方法1:os库—重命名移动版

# -*- coding: UTF-8 -*-
'''
@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_"
        # 你可以根据需要自定义命名规则
        new_name = "new_" + filename
        new_file = os.path.join(new_folder_path, new_name)
        # 重命名文件
        # os.rename(old_file, new_file)
        # 复制文件
        os.system(f"cp{old_file} {new_file}")
        print(f"Renamed '{filename}' to '{new_name}'")

方法2:os+shutil—重命名复制版

# -*- coding: UTF-8 -*-
'''
@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)  # 使用copy2以保留元数据
            print(f"Copied '{filename}' to '{new_name}'")

# 设置文件夹路径
folder_path = '文件'
new_folder_path = '新命名'

copy_files_to_new_folder(folder_path, new_folder_path)

方法3:pathlib—重命名移动版

# -*- coding: UTF-8 -*-
'''
@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_"
        # 你可以根据需要自定义命名规则
        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)  # 使用copy2以保留元数据
            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版本附赠

# -*- coding: UTF-8 -*-
'''
@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)  # 使用copy2以保留元数据
            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()

总结

  • 希望对初学者有帮助

  • 致力于办公自动化的小小程序员一枚

  • 希望能得到大家的【一个免费关注】!感谢

  • 求个 🤞 关注 🤞

  • 此外还有办公自动化专栏,欢迎大家订阅:Python办公自动化专栏

  • 求个 ❤️ 喜欢 ❤️

  • 此外还有爬虫专栏,欢迎大家订阅:Python爬虫基础专栏

  • 求个 👍 收藏 👍

  • 此外还有Python基础专栏,欢迎大家订阅:Python基础学习专栏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一晌小贪欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值