Rename multiple files using names in a text file

James Stroud jstroud at mbi.ucla.edu
Fri Sep 14 21:52:52 CEST 2007


rémi wrote:
> Hi,
> 
> I would like to rename files (jpg's ones) using a text file containing the
> new names...
> Below is the code that doesn't work :
> *****
> #!/usr/bin/python
> #-*- coding: utf-8 -*-
> from os import listdir, getcwd, rename
> import re
> list_names=['new_name1','new_name2']
> list_files = listdir(getcwd())
> filtre = re.compile("jpg$", re.IGNORECASE) 
> list_jpg = filter(filtre.search, list_files)
> #strip all element of list list_jpg
> list_jpg_strip=[]
> for nom in list_jpg:
> 	#print nom.strip()
> 	list_jpg_strip.append(nom.strip())
> #let's rename :
> i=0
> while i <= len(list_jpg_strip):
> 	rename(list_jpg_strip[i],list_names[i])
> 	i=i+1
> ****
> The error message is :
> File "ecm.py", line 17, in <module>
>     rename(list_jpg_strip[i],list_names[i])
> OSError: [Errno 2] No such file or directory
> and all files exists, I checked it hundred times ! :-s
> Do you have a clue ?
> Thanks a lot.
> Rémi.

Other than that your strip() is stripping off some whitespace that is 
part of the name, I really can't see the problem either, but did you try 
to add in the explicit path? E.g.:

path_to = getcwd()
list_files = listdir(path_to)
.
.
.
for nom in list_jpg:
   old_path = os.path.join(path_to, nom.strip())
   list_jpg_strip.append(old_path)
.
.
.
for old_path, new_name in zip(list_jpg_strip, list_names):
   new_path = os.path.join(path_to, new_name)
   rename(old_path, new_path)

James



More information about the Python-list mailing list