How to write string to file line by line python

Viewed 56

I have written the following code, when I print the output it is correct

  7.21: (1,2)->(5,8) 
  5.39: (5,8)->(10,10) 
 24.08: (10,10)->(34,12) 

But when I try to write to file I cannot work out how to obtain the same result. I want to print line by line with the padding as in the print function

But I get this from the file, all in one line 7.21: (1,2)->(5,8) 5.39: (5,8)->(10,10) 24.08: (10,10)->(34,12)


from math import sqrt

f = open('output.txt', 'w')
cord_list=[]
for i in range(len(my_coord)):
  for j in range(len(my_coord[i])):

    cord_list.append(my_coord[i][j])

a=0
b=1
c=0
d=1
for x in range (0,3):
  my_res=((cord_list[a]-cord_list[a+2])**2)+((cord_list[b]-cord_list[b+2])**2)
  a=a+2
  b=b+2
  my_res=sqrt(my_res)
  my_res=round(my_res, 2)
  

  print (f'{my_res: >10}: ({cord_list[c]},{cord_list[d]})->({cord_list[c+2]},{cord_list[c+3]}) ')
  string=(f'{my_res: >10}: ({cord_list[c]},{cord_list[d]})->({cord_list[c+2]},{cord_list[c+3]})')
  f.writelines(string) 
  c=c+2
  d=d+2

f.close()

1 Answers

add newline at the end \n

from math import sqrt

f = open('output.txt', 'w')
cord_list=[]
for i in range(len(my_coord)):
  for j in range(len(my_coord[i])):

    cord_list.append(my_coord[i][j])

a=0
b=1
c=0
d=1
for x in range (0,3):
  my_res=((cord_list[a]-cord_list[a+2])**2)+((cord_list[b]-cord_list[b+2])**2)
  a=a+2
  b=b+2
  my_res=sqrt(my_res)
  my_res=round(my_res, 2)
  

  print (f"{my_res: >10}: ({cord_list[c]},{cord_list[d]})->({cord_list[c+2]},{cord_list[c+3]}) \n")
  string=(f"{my_res: >10}: ({cord_list[c]},{cord_list[d]})->({cord_list[c+2]},{cord_list[c+3]})\n")
  f.writelines(string) 
  c=c+2
  d=d+2

f.close()
Related