我有一个包含 x,y,z 值的文件。我希望找到一种优雅的方式来打开并向每一行添加一个新值 id 并再次保存同一个文件。
def get_point_grid_id(x,y,x_min,y_max,x_dist,y_dist):
col = int((x - x_min)/x_dist)
row = int((y_max - y)/y_dist)
return (row, col)
前任
1 1 10
2 2 10
3 3 10
ID将是
get_point_grid_id(1,1,0,10,1,1)
(9, 1)
get_point_grid_id(2,2,0,10,1,1)
(8, 2)
get_point_grid_id(3,3,0,10,1,1)
(7, 3)
新文件将是
1 1 10 (9, 1)
2 2 10 (8, 2)
3 3 10 (7, 3)
我正在阅读 Stackoverflow 中的几种方法,并测试了几种方法。老实说,我已尝试保存新文件但未能成功。
我曾尝试过以下解决方案
with open(file_temp, "r+") as f:
for line in open(file_temp):
x,y,z = line.split()
id = get_point_grid_id(float(x),float(y),0,10,1,1)
element = [x,y,z,id]
newelement = " ".join([str(e) for e in element])+ "\n"
f.write(newelement)
但我收到此错误消息
Traceback (most recent call last):
File "<editor selection>", line 3, in <module>
ValueError: too many values to unpack
其中 newelement (真实数据)是
'481499.55 6244324.75 19.15 (377, 2909)\n'