By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,571 Members | 952 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,571 IT Pros & Developers. It's quick & easy.

Error: IndexError:list out of range

P: 1
when i am executing the following code i m getting IndexError:list out of range

Expand|Select|Wrap|Line Numbers
  1. import os;
  2. import sys;
  3. file1=open(sys.argv[1],"r").readlines() # 1_train.txt
  4. file2=open(sys.argv[2],"w")
  5. for i in range(0, len(file1)):
  6.     w=file1[i].split();
  7.      if(len(w)==3):
  8.         file2.write(w[0]+"_"+w[2]+"\t"+w[1]+"\n");
  9.     else:
  10.         file2.write("\n");
Apr 23 '12 #1
Share this Question
Share on Google+
1 Reply

bvdet
Expert Mod 2.5K+
P: 2,851
It would be helpful if you posted the complete traceback. My initial thought is you only gave it one argument. You can add print statements at strategic places to see what is taking place.

It would be more concise to iterate on the file object instead of a range. Something like:
Expand|Select|Wrap|Line Numbers
  1. file1=open(sys.argv[1],"r")
  2. for line in f:
  3.     w=line.split()
  4.     ................
Apr 23 '12 #2

Post your reply

Sign in to post your reply or Sign up for a free account.