[Tutor] renaming files within a directory

davidwilson at Safe-mail.net davidwilson at Safe-mail.net
Mon Jul 27 14:26:23 CEST 2009


Here is the updated viersion:

---

import glob
import csv
from os import rename


countries = {}
reader = csv.reader(open("countries.csv"))
for row in reader:
    code, name = row
    countries[name] = code

files = set([file for file in glob.glob('Flag_of_*.svg')])

for file in files:
    file = file[8:-4]
    if file.startswith('the_'):
	file = file[4:]
    if countries.has_key(file):
	b = 'flag-'+ countries[file] + '.svg'
	print b
	rename(file, b)

But I cannot get the rename to take effect and I get an error:

$ python rename_svg.py 
Uganda flag-ug.svg
Traceback (most recent call last):
  File "rename_svg.py", line 21, in <module>
    rename(file, b)
OSError: [Errno 2] No such file or directory

What am I missing?

-------- Original Message --------
From: Kent Johnson <kent37 at tds.net>
Apparently from: kent3737 at gmail.com
To: davidwilson at safe-mail.net
Cc: mail at timgolden.me.uk, tutor at python.org
Subject: Re: [Tutor] renaming files within a directory
Date: Mon, 27 Jul 2009 07:01:32 -0400

> On Mon, Jul 27, 2009 at 5:10 AM, <davidwilson at safe-mail.net> wrote:
> 
> > files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')])
> > print len(files)
> >
> > for file in files:
> >    file = file.strip('.svg')
> >    print file
> > #    if countries.has_key(file):
> > #       print file
> >
> > When I run this I get:
> >
> > Flag_of_Uganda
> > ...
> >
> > The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State
> >
> > Also, How do I remove 'Flag_of', 'Flag_of_the_'
> 
> I suggest you use glob.glob() instead of os.listdir():
> 
> files = glob.glob('Flag_of_*.svg)
> 
> Then you know that each file name starts with Flag_of_ and ends with
> .svg. To remove them, since they are fixed strings you can just use
> slicing;
> file = file[8:-4]
> if file.startswith('the_'):
>   file = file[4:]
> 
> Kent


More information about the Tutor mailing list