gihansalith gihansalith - 4 months ago 8
Python Question

Need explanation some terms in python code

this is my code

'''Nimal,30,60
Saman,80,45
Upali,100,80
above text is in input.txt
'''
f1 = open('input.txt','r')
f2 = open('output.txt','w')
line = f1.readline()
while(line):
data = (line.strip()).split(',')
total = float(data[1])+float(data[2])
f2.write('{},{},{},{}\n'.format(data[0],data[1],data[2],total))
line=f1.readline()
f1.close()
f2.close()


I need to know
while(line)
how become true and what happen in below line

f2.write('{},{},{},{}\n'.format(data[0],data[1],data[2],total))

Answer

In your example, line is a string. In python, a string will be evaluated as False if it's an empty string, say ''. Otherwise, it will be evaluated as True.

What f2.write('{},{},{},{}\n'.format(data[0],data[1],data[2],total)) does is to fill the four {} with the corresponding values given in the format function, and then write out to f2. For example, f2.write('{},{},{},{}\n'.format('Nimal', 1, 2, 3)) will be formalized as a string 'Nimal,1,2,3\n' without quotes, and then write this string into file f2.

Comments