1

我有一个包含 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' 
4

1 回答 1

2

您可以通过模块模拟所需的行为,fileinput但请记住,它将在后台创建原始 10GB+ 文件的备份副本:

#! /usr/bin/env python
import fileinput

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)

input_file = "test.dat"
#
# Add mode='rb' to the arguments of fileinput.input() if you are
# using a binary file on operating systems that differentiate 
# between binary and text files (e.g. Microsoft Windows). 
#
for line in fileinput.input(input_file, inplace=True):
    columns = line.split()
    if 3 == len(columns):
        x, y, z = columns
        id = get_point_grid_id(float(x),float(y),0,10,1,1)
        print "{0} {1} {2} {3}".format(x, y, z, id)

inplace传递给的参数fileinput.input触发魔法。

于 2013-02-22T18:45:53.483 回答