0
点赞
收藏
分享

微信扫一扫

Python 重命名文件


import os
import pandas as pd


def readExcel(excelPath, oldKey, newKey):
    df = pd.read_excel(excelPath, dtype={newKey: str, oldKey: str})
    oldNames = df[oldKey].tolist()
    newNames = df[newKey].tolist()
    return oldNames, newNames

def renameFile(imagePath, oldNames, newNames):
    for i in range(len(oldNames)):
        if not os.path.exists(os.path.join(imagePath, oldNames[i] + '.jpg')):
            print(imagePath + '\\' + oldNames[i] + '.jpg not exists')
            continue
        oldName = os.path.join(imagePath, oldNames[i] + '.jpg')
        newName = os.path.join(imagePath, newNames[i] + '.jpg')
        os.rename(oldName, newName)

if __name__ == '__main__':
    # imagePath: 图片路径,excelPath: excel路径
    imagePath = r'image'
    excelPath = r'数据.xlsx'
    # Step 1: 读取excel
    oldNames, newNames = readExcel(excelPath, '字段1', '字段2')
    # Step 2: 重命名文件
    renameFile(imagePath, oldNames, newNames)

import os

def renameFile(imagePath, txtPath):
    with open(txtPath, 'r') as f:
        lines = f.readlines()
        for line in lines:
            oldName, newName = line.strip().split(' ')
            if not os.path.exists(os.path.join(imagePath, oldName + '.jpg')):
                print(imagePath + '\\' + oldName + '.jpg not exists')
                continue
            oldName = os.path.join(imagePath, oldName + '.jpg')
            newName = os.path.join(imagePath, newName + '.jpg')
            os.rename(oldName, newName)
    f.close()

if __name__ == '__main__':
    imagePath = r'image'
    txtPath = r'data.txt'
    renameFile(imagePath, txtPath)


举报

相关推荐

0 条评论