Start New Discussion within our Software Development Community

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]
		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

You should run it from command line as

python . 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.

Thank you.

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

- WolfShield

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.

This question has already been answered. Start a new discussion instead.