重命名文件夹中的图像 [英] Renaming images in folder

查看:142
本文介绍了重命名文件夹中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据.csv中存储的名称重命名文件夹中的图像.

I am trying to rename images in a folder based on names stored in a .csv.

我真的不明白下面的代码是什么问题.图片和.csv位于同一文件夹中

I realy don't understand what's the issue with below code. The images and .csv are in the same folder

with open('labels.csv', 'r') as f:
    lines = csv.reader(f, delimiter = ',')
    for line in lines:
        os.rename(line[0], line[1] + str('.png'))

我遇到错误.

FileNotFoundError: [WinError 2] The system cannot find the file specified: '100000.png' -> '1.png'

我过去(前一段时间)尝试过此方法,并且工作了.是.csv,逻辑还是图像中的问题?

I tried this in the past (a while ago) and worked. Is the issue in the .csv, the logic or the images?

推荐答案

您应提供绝对路径.您可以通过变量

You should provide absolute path.you can append directory path by variable

 os.path.dirname(__file__)

它将为您提供当前脚本文件路径的目录.随后,您需要连接目录路径和当前文件名(os.path.join())

It will give you current script file path's directory. Subsequently, you need to join directory path and current file name(os.path.join())

您应该将CSV文件目录作为当前目录. os.chdir()是函数.如果需要代码作为帮助,请告诉我.

You should make CSV files directory as current directory. os.chdir() is function. Please let me know if you need code as help.

import os.path
import csv
current_directory =  os.path.dirname(__file__)
csv_file_path = os.path.join(current_directory,'labels.csv')
with open(csv_file_path, 'r') as f:
    lines = csv.reader(f, delimiter = ',')
    for line in lines:        
        current_file_path = os.path.join(current_directory,line[0])
        renamed_file_path = os.path.join(current_directory,line[1] + ".png")
        os.rename(current_file_path, renamed_file_path)

请把您的.py文件放在同一目录中.

Please put your .py file in the same directory.

这篇关于重命名文件夹中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆