I am learning Python and I have an exercise to work through:
Write a program which will read in lines from a file and select the first three fields (separated by blank space). The program should write a file called error which contains lines which look like Line 362 did not have 3 fields, to identify those which did not have 3 fields. The program should then write, into a file called output, the first three fields in the form of a string of width 10, followed by two floats of width 10 each with 3 places after the decimal point. In case this is not possible, the fields should be written as strings of width 10.
I have done half of it, but I can't get the list items into the error exceptions report. I don't get any error messages; I just get an empty file.
My exceptions data is displayed in Python but the write output is missing.
This is my code:
file = open("question3.txt",'r')
read = file.read()
file.close()
print(read)
#This is the list of sentences that form the list 'read'
#I need to analyse these list items.
array = read.splitlines()
print(array)
for item in array:
if(item.count(" "))<3:
exception = str(item)
f = open('error.txt','w')
f.write(exception)
print(exception)
f.close()
How can I resolve this? I don't need a full answer to the question, just a suggestion as to how I can get the 'short list fields' I have identified into the text file.
Thank you!