首页 > 解决方案 > 在文本文件的行尾写入字符串

问题描述

我想在文本文件的每一行末尾写一个字符串。基本上我想添加 Minx 和 Maxx 值并将结果附加到行尾。使用我的代码,它只添加第一行的最小值和最大值,并将其附加到文件末尾的新行上。在 Python 中实现这一点的最简单方法是什么?

文本文件包含如下内容:

Distance1Mean1=5.40530mm StDev1=0.00543 Median1=5.40392mm Min1=5.39694mm Max1=5.41789mm DeltaMeanMedian1=0.00138mm DeltaMax1=0.02095mm NumberOfReadings=33, 
Distance2Mean2=6.40218mm StDev2=0.00226 Median2=6.40239mm Min2=6.39890mm Max2=6.40588mm DeltaMeanMedian2=-0.00021mm DeltaMax2=0.00698mm NumberOfReadings=33,* 

我的代码:

with open("Example1.txt", "r+") as f:
#line=f.readline()
    string=[]
    for line in f:
        if line.startswith('Distance'):
            word1=line[63:70]
            word2=line[78:85]
            string = [line[63:70], line[78:85]]
            a = float(string[0])
            b = float(string[1])
            c = a + b
            f.write(str(c))
f.close()

标签: pythonpython-3.xfile

解决方案


您可以使用endprint 的 kwarg,如下所示:

for x in range(5):
    print('Line'+str(x),end=' Are you still there?\n')

这会产生一个输出:

Line0 Are you still there?
Line1 Are you still there?
Line2 Are you still there?
Line3 Are you still there?
Line4 Are you still there?

我相信这适用于您的问题。


推荐阅读