[Tutor] IndexError: list index out of range : f2.write(col[0] +
'\t' + col[1] + '\n')
Max Noel
maxnoel_fr at yahoo.fr
Wed Nov 3 18:02:22 CET 2004
On Nov 3, 2004, at 16:12, kumar s wrote:
> def cutter (f1,f2):
> file = open(f1,'r')
> file2 = open(f2,'w')
> fopen = file.read()
> flist = split(fopen,'\n')
> for i in range(len(flist)):
> col = split(flist[i],'\t')
> file2.write(col[0] + '\t' + col[1] + '\t' + col[3] +
> '\n' )
> file2.close()
>
>
>>>> cutter('gene_data.txt','test1.txt')
>
> Traceback (most recent call last):
> File "<pyshell#44>", line 1, in -toplevel-
> cutter('gene_data.txt','test1.txt')
> File "<pyshell#42>", line 8, in cutter
> file2.write(col[0] + '\t' + col[1] + '\t' + col[3]
> + '\n' )
> ValueError: I/O operation on closed file
>
>
> Why am I getting ValueError and I/O. Why shouldnt I
> close file2.close()?
That's because you're closing the file after each line. You should
close it after the for loop instead.
Also, you're using C-style for loops. A more elegant and
memory-efficient (the way you're doing it, you load the whole file in
memory, which is a Bad Thing if it's a big file) way to write your
function using the file iterator:
def cutter(sourceName, destName):
source = open(sourceName) # Read-only is the default mode
dest = open(destName, 'w')
for line in source:
col = split(line, '\t')
dest.write('\t'.join(col) + '\n')
dest.close()
One last thing: you're naming your source file stream 'file', which is
not a good idea given that file is a Python built-in class (for which
open is an alias).
>
>
> 2nd Question:
>
>>>> cutter('gene_data.txt','test1.txt')
>
> Traceback (most recent call last):
> File "<pyshell#47>", line 1, in -toplevel-
> cutter('gene_data.txt','test1.txt')
> File "<pyshell#46>", line 8, in cutter
> file2.write(col[0] + '\t' + col[1] + '\t' + col[3]
> + '\n' )
> IndexError: list index out of range
>>>>
>
>
>
> Now, why am I getting IndexError: list out of range.
> What is the problem. I got the result but an error is
> not so good. Can any one help me explaing the
> situation.
That probably means that on the line for which you're getting the
error, len(col) < 4.
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting
and sweating as you run through my corridors... How can you challenge a
perfect, immortal machine?"
More information about the Tutor
mailing list