954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Index Out Of Range

So,
I am working with some code I don't understand. Here is the file:

import sys
import os

def change_ext(directory, old_ext, new_ext):
	for f in os.listdir(sys.argv[1]):
		base, ext = os.path.splitext(f)
		if ext[1:] == sys.argv[2]:
			os.rename(f, "%s.%s" % (base, sys.argv[3]))
			
if __name__ == '__main__':
	if len(sys.argv) < 4:
		print "usage: %s directory old_ext new_ext" % sys.argv[0]
		sys.exit(1)
		change_ext(sys.argv[1], sys.argv[2], sys.argv[3])


When I run it through Jython in Command Prompt as follows:

import chext

chext.change_ext(".", "foo", "java")


It gives me the error:

for f in os.listdir(sys.argv[1]):  
Index Error: index out of range: 1


How do I fix this?

-WolfShield

WolfShield
Posting Whiz in Training
236 posts since Oct 2010
Reputation Points: 28
Solved Threads: 4
 

You should run it from command line as

python chext.py . foo java

But really you should fix the function as it is not using the parameters properly:

def change_ext(directory, old_ext, new_ext):
	for f in os.listdir(directory):
		base, ext = os.path.splitext(f)
		if ext[1:] == old_ext:
			os.rename(f, "%s.%s" % (base, new_ext))


Also you should fix the hard tabs to 4 space soft tabs.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Ahh,
Thank you.

Thanks for the coding advice. I've heard the four spaces vs the tab before, why is that?

- WolfShield

WolfShield
Posting Whiz in Training
236 posts since Oct 2010
Reputation Points: 28
Solved Threads: 4
 

Mixing the two styles produces hard to debug problems in indention and ugly code with big tabs, so Python convention is spaces. It is not an absolute truth as in Go language for example convention is hard tabs. Read PEP8 document and try to use it as long as it makes sense. That makes your code easier to understand for you and others. You might also try to dicipline yourself for few usefull other coding practices, for example using plural names for sequences and verb names for action performing functions.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Thank you very much,
I will do my best. Until next time...

- WolfShield

WolfShield
Posting Whiz in Training
236 posts since Oct 2010
Reputation Points: 28
Solved Threads: 4
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: