I have this simple code which is really just to help me understand how Python I/O works:
inFile = open("inFile.txt",'r')
outFile = open("outFile.txt",'w')
lines = inFile.readlines()
first = True
for line in lines:
if first == True:
outFile.write(line) #always print the header
first = False
continue
nums = line.split()
outFile.write(nums[3] + "\n") #print the 4th column of each row
outFile.close()
My input file is something like this:
#header
34.2 3.42 64.56 54.43 3.45
4.53 65.6 5.743 34.52 56.4
4.53 90.8 53.45 134.5 4.58
5.76 53.9 89.43 54.33 3.45
The output prints out into the file just as it should but I also get the error:
outFile.write(nums[3] + "\n")
IndexError: list index out of range
I’m assuming this is because it has continued to read the next line although there is no longer any data?
Others have already answered your question. Here is a better way to “always print out the file header”, avoiding testing for
firstat every iteration:A couple things are going on here:
The
withexpression is a convenient way to open files because it automatically closes the files even if an exception occurs and the with block exits early.Note: In Python 2.6, you will need to use two
withstatements, as support for multiple contexts was not added until 2.7. e.g:The
fileobject is an iterator that gets consumed. Whenreadline()is called, the buffer position advances forwards and the first line is returned.As mentioned before, the
fileobject is an iterator, so you can use it directly in aforloop.