1.11M Members

Index Out Of Range

 
0
 

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

 
0
 

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.

 
0
 

Ahh,
Thank you.

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

- WolfShield

 
0
 

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.

 
0
 

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

- WolfShield

Question Answered as of 3 Years Ago by pyTony
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: