用python重命名多个文件名

2024-09-30 04:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含学生照片的文件夹,命名格式如下:

StudentID_Name-Number

例如:37_GOWDA-Rohan-1204-06675

我只想保留37,有些学生可能有更长的ID(12365857……)

如何使用python实现这一点,我假设我需要os


Tags: name文件夹idnumberos格式命名学生
1条回答
网友
1楼 · 发布于 2024-09-30 04:31:49

您可以使用这样的方法列出目录的所有内容,提取学生id,查找文件类型,创建新名称并将其保存在同一目录中:

import os

# full directory path to student pictures
student_pic_path = 'full directory path to student pics'

# get all student picture filenames from path
fnames = os.listdir(student_pic_path)

# iterate over each picture
for fname in fnames:
    # split by underscore and capture student id name
    new_name = fname.split('_')[0]
    # get the file type
    file_type = fname.split('.')[-1]
    # append file type to new name
    new_name = '{}.{}'.format(new_name, file_type)
    os.rename(os.path.join(student_pic_path, fname), 
              os.path.join(student_pic_path, new_name))

相关问题 更多 >

    热门问题