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

Recommended Answers

All 4 Replies

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.

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

- WolfShield

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.