How to change image name with python?

Asked

Viewed 35 times

-1

I want to change/change the name of a set of images.

I have the python code that does this, the problem is that it generates as follows "123image.jpg" and that wanted "image123.jpg". How to adjust this in code?

import os 

path = '/Users/gustavo/projects/dump/tf_files/locate_vaccancies/vaccancy'
files = os.listdir(path)


for index, file in enumerate(files):
    os.rename(os.path.join(path, file), os.path.join(path, 'vaccancy'.join([str(index), '.jpg'])))

1 answer

0

To do this you can use the code below:

import os
from shutil import move

Defining the path and extension of files

caminho = 'C:/caminho/para_as_imagens'
ext = '.jpg'

Taking the list of file names in the given folder

arquivos = os.listdir(caminho)

Checking that files end with the desired extension

arquivos = [arquivo for arquivo in arquivos if arquivo.endswith(ext)]

This is where the file name change happens

[move(arquivo, f'imagem{i}.jpg') for i, arquivo in enumerate(arquivos)]

Code

import os
from shutil import move

caminho = 'C:/caminho/para_as_imagens'
ext = '.jpg'

arquivos = os.listdir(caminho)
arquivos = [arquivo for arquivo in arquivos if arquivo.endswith(ext)]

[move(arquivo, f'imagem{i}.jpg') for i, arquivo in enumerate(arquivos)]
  • Thanks, I’ll try it.

  • This is Imonferrari speaking. I circled my python file and it pointed out syntax error here: [move(file, f'g{i}.jpg') for i, file in enumerate(files)] Syntaxerror: invalid syntax In single quotes after jpg

  • Which version of python do you use? Maybe this solves the problem in your case: [move(arquivo, 'imagem'+str(i)+'.jpg') for i, arquivo in enumerate(arquivos)]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.