python - 在文本文件的行尾写入字符串
问题描述
我想在文本文件的每一行末尾写一个字符串。基本上我想添加 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()
解决方案
您可以使用end
print 的 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?
我相信这适用于您的问题。
推荐阅读
- facebook-graph-api - 如何代表用户点赞 - Facebook Workplace API
- ios - 如何更改 UIAlertAction 的标题
- android - 无法通过图表点击事件区分两个片段
- javascript - OAuth2 HTTPRequest CORS 策略
- xcode - 为什么提交更新显示在主文件夹而不是主分支中?Xcode
- python-3.x - 用另一个二维数组中的列替换 2D numpy 数组中的列
- opengl - Xamarin.Forms OpenGLView 在 XAML 页面中使用时不起作用
- python - 如何在 pyqtgraph 中为单个 PlotItem 设置背景颜色?
- python - 将值分配给 2D numpy 数组作为索引函数的有效方法是什么
- android - 使用意图启动新活动时未显示布局