SunQuest
           Python Programming
 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me
Go Back   Dev Shed ForumsProgramming LanguagesPython Programming

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Dev Shed Forums Sponsor:
SlickEdit: Code in over 40 languages across 7 platforms. SlickEdit’s unmatched power, speed, and flexibility allows even the most accomplished developers to write better code faster. Download a free trial today!
  #1  
Old October 22nd, 2003, 12:29 AM
Random Random is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 65 Random User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 39 m 56 sec
Reputation Power: 5
How to avoid index out of range error?

How to switch places two names in a long file name?
I have a directory with lots of files (don't know how many), where I want
to switch first name with second but leave the remaing names as they are. So if the file name is like that

First Second Description it should become
Second First Description

I know this must be really simple so this is what I tried to do.

Code:
import os, string 
count = 0 
for title in os.listdir('c:/files'): 
   a = string.split(title) 
   b = len(a[0]) + len(a[1]) + 1 
   newstring = a[1] + ', ' + a[0] + title[-(len(title)-b):] 
   os.rename('c:/files/' + title,'c:/files/' + newstring) 
   count = count + 1 
print count 


Well this code worked if I had a couple of files but failed with quantity
with "IndexError: list index out of range" error. Please tell me how to fix this or rewrite it better.

Thanks
Random

Reply With Quote
  #2  
Old October 22nd, 2003, 07:15 AM
FLNHST FLNHST is offline
404 Error
Dev Shed Newbie (0 - 499 posts)
 
Join Date: May 2002
Location: http://hester.dns2go.com
Posts: 18 FLNHST User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 52 m 3 sec
Reputation Power: 0
Code:

test_list = ['This','is','a','Test']

if test_list.__contains('is') == 1:
      print 'True'
else:
      print 'False'

Reply With Quote
  #3  
Old October 22nd, 2003, 07:16 AM
FLNHST FLNHST is offline
404 Error
Dev Shed Newbie (0 - 499 posts)
 
Join Date: May 2002
Location: http://hester.dns2go.com
Posts: 18 FLNHST User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 52 m 3 sec
Reputation Power: 0
oops, error in the reply from me, __contains must be __contains__

Reply With Quote
  #4  
Old October 22nd, 2003, 08:19 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 18 m 50 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
I've reworked your code, this new script has been tested it with up to 30 files without a glitch so it should work fine!? I'm guessing the reason your program fails at a sertain point is that not all files in the directory fit a standard partern (so can't be parsed in the same way)

The following is a line by line explination of this script:

1. shebang pointing at python
3. import the os module
5. set the default directory (./ is the dir which our program is in)
6. get a list of all the files in dir which fit a basic pattern (you could make this more accurate using regex)
8. loop though each filename in our list ('filenames')
9. split the filename on only the first two spaces (using the built-in string method split())
10. create the new format for our file using string formating
11. rename 'name'
13. print the number of files in filenames using len
15. wait for the user to press enter before exiting..

Code:
#!/usr/bin/env python

import os

directory = './'
filenames = filter(lambda x: x.count(' ') >= 2, os.listdir(directory))

for name in filenames: 
	name1 = name.split(' ', 2)  
	name2 = '%s %s %s' % (name1[1], name1[0], name1[2])
	os.rename(directory + name, directory + name2)

print len(filenames)

raw_input('Press ENTER to exit..')


FLN, in Python 2.x+ You can do the same thing with the 'in' keyword i.e 'is' in list.. just thought i'd mention it

Hope this helps,
Mark.
__________________
programming language development: www.netytan.com Hula


Last edited by netytan : October 22nd, 2003 at 08:28 AM.

Reply With Quote
  #5  
Old October 22nd, 2003, 08:35 AM
cvchen cvchen is offline
Hi, I'm Calvin
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2003
Location: LosAngeles, SanDiego, Houston
Posts: 50 cvchen User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 m 7 sec
Reputation Power: 5
here's what i did

i tried to keep your code format where i could

Code:
import os, string 
count = 0 
for title in os.listdir('c:/files'): 
   a = string.split(title)
   newstring = '%s %s %s'%(a[1],a[0],string.join(a[2:]))
   os.rename('c:/files/' + title,'c:/files/' + newstring) 
   count = count + 1 
print count


i used string.join() because i did not want to assume that all your files would have three tokens when split by spaces, perhaps there are some files that have more than two spaces? if not, if all your files only have three tokens when split by spaces, i'd use netytan's code instead... but if there are files that have more than three tokens when split by spaces, string.join() as i used it is the way to go... it works either way, but if there are only three space delimited tokens then string.join() is a bit overkill.

Reply With Quote
  #6  
Old October 22nd, 2003, 08:38 AM
cvchen cvchen is offline
Hi, I'm Calvin
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2003
Location: LosAngeles, SanDiego, Houston
Posts: 50 cvchen User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 m 7 sec
Reputation Power: 5
oh yeah

count = count + 1

can be replaced by

count += 1

i don't know... somehow that's just more visually pleasing to me lol...

you know, (this has nothing to do with your program or question) i really am curious as to why python doesn't have an icrementer and decrementer operator like ++ or --

count++ to me looks better still than count+=1

ok i'm done rambling

Reply With Quote
  #7  
Old October 22nd, 2003, 08:54 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 18 m 50 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
Me too i've asked that question to myself a few times, the answer i was given by strike (if i remember this correctly) was that +=/-= is more flexable than ++/-- but personally, i like the whole icrementer and decrementer operator idea.. ah well

In CV's program he used string.join(), but you can also use 'string object'.join() which will do the exactly same thing . I havn't touched the string module in ages!

For more info on this you can type help(str) at Pythons interactive prompt, this will give you a list of the internals and methods for the string type, this also works for other types/modules/functions i.e. lists, tuples and dicts etc.

Mark.

Reply With Quote
  #8  
Old October 22nd, 2003, 09:46 AM
cvchen cvchen is offline
Hi, I'm Calvin
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Sep 2003
Location: LosAngeles, SanDiego, Houston
Posts: 50 cvchen User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 m 7 sec
Reputation Power: 5
yeah...

and i suppose flexibility is pythonic, or something

Reply With Quote
  #9  
Old October 22nd, 2003, 09:55 AM
netytan's Avatar
netytan netytan is offline
Hello World :)
Dev Shed Frequenter (2500 - 2999 posts)
 
Join Date: Mar 2003
Location: Hull, UK
Posts: 2,529 netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level)netytan User rank is Second Lieutenant (5000 - 10000 Reputation Level) 
Time spent in forums: 1 Week 2 Days 17 h 18 m 50 sec
Reputation Power: 63
Send a message via ICQ to netytan Send a message via AIM to netytan Send a message via MSN to netytan Send a message via Yahoo to netytan
uh huh, but theres no halm in having both surly!? Ah well, maybe one day they'll put one in the mix..

Mark.

Reply With Quote
  #10  
Old October 22nd, 2003, 07:42 PM
Random Random is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Aug 2003
Posts: 65 Random User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 1 h 39 m 56 sec
Reputation Power: 5
Thanks Mark and cvchen for your help. This is one of the most helpful forums I have visited. Now it's time to learn from your code and see how it works.
Again Thanks.
Random

Reply With Quote
  #11  
Old October 28th, 2003, 09:36 AM
lazy_yogi lazy_yogi is offline
Contributing User
Dev Shed Newbie (0 - 499 posts)
 
Join Date: Mar 2003
Posts: 325 lazy_yogi User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 7 h 58 m 36 sec
Reputation Power: 6
The main things I dislike about perl (and some other languages, but epecially prevalient in perl) is that there are so many ways to do the same task.

You can come back after a few months/years and look at perl code and have to look up every second line and figure out what it means.

The thing I love about python is that in many cases there is only one way to do something.
It makes the code almost immediately readable since there is only one way to do it.

Cheers,
Eli

Reply With Quote
Reply

Viewing: Dev Shed ForumsProgramming LanguagesPython Programming > How to avoid index out of range error?


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump


Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 





© 2003-2008 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway