You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何实现带对齐格式的字符串逐行写入文件

问题解决方案

根因说明

print()函数默认会在输出内容末尾自动追加换行符\n,但直接调用文件对象的写入方法时,不会自动添加任何换行符,所以所有行内容会直接拼接成一整行写入文件,你的对齐格式本身是正确的,只需要补全换行逻辑即可。

代码修改方法

两种修改思路都可以实现和控制台输出完全一致的效果:

方案1:手动添加换行符写入

在构造的字符串末尾补加换行符\n即可,同时注意写入单个字符串用write()方法更合理(writelines()是用来写入字符串序列的方法):

# 循环内修改为如下代码
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]})\n'
f.write(string) 

方案2:直接复用print输出到文件

更简单的方式是直接用print的file参数写入文件,不需要额外构造字符串,完全复用已经调试好的打印逻辑:

# 循环内修改为如下代码
output_str = f'{my_res: >10}: ({cord_list[c]},{cord_list[d]})->({cord_list[c+2]},{cord_list[c+3]}) '
print(output_str) # 控制台输出
print(output_str, file=f) # 直接写入文件,自动带换行

优化建议

推荐用with上下文管理器操作文件,会自动处理文件关闭逻辑,避免忘记调用close()导致的文件异常:

from math import sqrt

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
with open('output.txt', 'w') as f:
  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)
    output_str = f'{my_res: >10}: ({cord_list[c]},{cord_list[d]})->({cord_list[c+2]},{cord_list[c+3]}) '
    print(output_str)
    print(output_str, file=f)
    c=c+2
    d=d+2

内容的提问来源于stack exchange,提问作者Emilia Delizia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:15:08