我有一个.txt文件,我试图在每行的末尾添加浮点数,其值要比最后一行增加。 这是我在.txt文件中所拥有的:
>520.980000 172.900000 357.440000
>320.980000 192.900000 357.441000
>325.980000 172.900000 87.440000
我正在尝试获得以下结果:
>520.980000 172.900000 357.440000 1.1
>320.980000 192.900000 357.441000 1.2
>325.980000 172.900000 87.440000 1.3
但是似乎无法弄清楚如何迭代和增加数据。
编辑:
@Daweo建议,由于注释部分中的格式问题,我将注释放入了编辑部分。 因此,我有一个如下的帧序列,我想给每个序列组一个数字,并增加以下数值,例如:索引为0的组(第一列)我将在末尾加1每行,索引为1的下一行,我将在每行末尾添加2,依此类推:
0 0 0 0 -1.793451 296.744956 161.752147 455.226042 292.372804
0 1 0 0 -1.936993 737.619499 161.531951 931.112229 374.000000
0 2 0 0 -2.523309 1106.137292 166.576807 1204.470628 323.876144
1 -1 -1 -1 -10.000000 228.120000 183.030000 258.830000 217.340000
1 -1 -1 -1 -10.000000 59.210000 191.300000 137.370000 227.430000
1 0 0 0 -1.796862 294.898777 156.024256 452.199718 284.621269 2.000000
1 1 0 0 -1.935205 745.017137 156.393157 938.839722 374.000000 1.739063
1 2 0 0 -2.530402 1138.342096 160.872449 1223.338201 324.146788
2 -1 -1 -1 -10.000000 236.270000 175.500000 267.210000 211.030000
2 -1 -1 -1 -10.000000 68.906000 183.810000 145.870000 224.020000
2 0 0 0 -1.800343 293.093560 150.470149 449.259225 277.104290 2.000000
答案 0 :(得分:1)
我将按照以下方式进行操作:
假设您有文件input.txt
:
520.980000 172.900000 357.440000
320.980000 192.900000 357.441000
325.980000 172.900000 87.440000
然后:
from decimal import Decimal
import re
counter = Decimal('1.0')
def get_number(_):
global counter
counter += Decimal('0.1')
return " "+str(counter)+'\n'
with open("input.txt","r") as f:
data = f.read()
out = re.sub('\n',get_number,data)
with open("output.txt","w") as f:
f.write(out)
之后的output.txt
是:
520.980000 172.900000 357.440000 1.1
320.980000 192.900000 357.441000 1.2
325.980000 172.900000 87.440000 1.3
请注意,我使用Decimal
来防止出现浮动问题(例如something.999999 ...)。我使用正则表达式(re
)查找换行符(\n
),并通过将函数作为第二个re.sub
参数传递而将其替换为后续数字。
答案 1 :(得分:0)
没有其他模块(不是您应该避免使用它们!):
with open("numbers.txt", "rt") as fin:
with open("numbers_out.txt", "wt") as fout:
counter = 1.0
for line in fin:
counter += 0.1
fout.write(f"{line.rstrip()} {counter:.1f}\n")
numbers_out.txt:
>520.980000 172.900000 357.440000 1.1
>320.980000 192.900000 357.441000 1.2
>325.980000 172.900000 87.440000 1.3
答案 2 :(得分:-1)
尝试一下:
f = open('file.txt', mode='r')
a_file = f.readlines()
f.close()
f = open('outfile.txt', mode='w')
SOMENUMBER = '777.88'
for row in a_file:
n_row = row.replace('\n', ' ')
n_row += SOMENUMBER+'\n'
print(row[-1])
f.write(n_row)
f.close()
在
520.980000 172.900000 357.440000
320.980000 192.900000 357.441000
325.980000 172.900000 87.4400000
出
520.980000 172.900000 357.440000 777.88
320.980000 192.900000 357.441000 777.88
325.980000 172.900000 87.4400000 777.88