#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    74
    Rep Power
    12

    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
  2. #2
  3. No Profile Picture
    404 Error
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2002
    Location
    http://hester.dns2go.com
    Posts
    18
    Rep Power
    0
    Code:
    test_list = ['This','is','a','Test']
    
    if test_list.__contains('is') == 1:
          print 'True'
    else:
          print 'False'
  4. #3
  5. No Profile Picture
    404 Error
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2002
    Location
    http://hester.dns2go.com
    Posts
    18
    Rep Power
    0
    oops, error in the reply from me, __contains must be __contains__
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    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.
    Last edited by netytan; October 22nd, 2003 at 08:28 AM.
    programming language development: www.netytan.com Hula

  8. #5
  9. No Profile Picture
    Hi, I'm Calvin
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Location
    LosAngeles, SanDiego, Houston
    Posts
    50
    Rep Power
    12

    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.
  10. #6
  11. No Profile Picture
    Hi, I'm Calvin
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Location
    LosAngeles, SanDiego, Houston
    Posts
    50
    Rep Power
    12

    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
  12. #7
  13. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    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.
    programming language development: www.netytan.com Hula

  14. #8
  15. No Profile Picture
    Hi, I'm Calvin
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2003
    Location
    LosAngeles, SanDiego, Houston
    Posts
    50
    Rep Power
    12

    yeah...


    and i suppose flexibility is pythonic, or something
  16. #9
  17. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    uh huh, but theres no halm in having both surly!? Ah well, maybe one day they'll put one in the mix..

    Mark.
    programming language development: www.netytan.com Hula

  18. #10
  19. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2003
    Posts
    74
    Rep Power
    12
    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
  20. #11
  21. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Posts
    325
    Rep Power
    12
    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

IMN logo majestic logo threadwatch logo seochat tools logo