简体   繁体   English

如何将字符串逐行写入文件python

[英]How to write string to file line by line python

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)但是我从文件中得到了这个,全部在一行中 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()

add newline at the end \\n在末尾添加换行符\\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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM