首页  >  文章  >  后端开发  >  如何使用 Python 重命名目录中的多个文件

如何使用 Python 重命名目录中的多个文件

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-24 04:41:30958浏览

How to Rename Multiple Files in a Directory Using Python

使用 Python 重命名目录中的多个文件

如果手动完成,重命名目录中的多个文件可能是一项繁琐的任务。然而,Python 提供了多种选项来自动化此过程,使其更加高效和准确。

方法:

使用 os.path.split

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    # Split the filename and extension
    filename, ext = os.path.splitext(file)

    # Modify the filename
    modified_filename = filename.split('_')[1]

    # Combine the modified filename with the extension
    new_file = modified_filename + ext

    # Rename the file
    os.rename(os.path.join(folder, file), os.path.join(folder, new_file))

使用字符串操作:

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    if file.startswith('CHEESE_'):
        # Remove 'CHEESE_' from the filename
        new_file = file[7:]

        # Rename the file
        os.rename(os.path.join(folder, file), os.path.join(folder, new_file))

使用 os.rename

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    if file.startswith('CHEESE_'):
        # Get the new filename
        new_file = file[7:]

        # Use os.rename() to change the filename
        os.rename(os.path.join(folder, file), os.path.join(folder, new_file))

全部这些方法实现了重命名目录中的文件、删除“CHEESE_”前缀并保留原始扩展名的预期结果。

以上是如何使用 Python 重命名目录中的多个文件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn