2013-02-22 81 views
1

我有一个带有x,y,z值的文件。我希望找到一种优雅的方式打开并为每行添加一个新的值,并再次保存相同的文件。python读取文件,为每行保存一个新列保存同一个文件

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) 

我在#1几个办法读,我测试的几种方法。我诚实地说,我已经尝试过,但未能保存新文件。

我曾试图followig解决方案

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' 
+0

写入一个单独的文件,然后重新命名回来! – 2013-02-22 17:38:27

+0

是的解决方案,但文件已经很大(超过10 GB) – 2013-02-22 17:40:10

+0

块和切片! – 2013-02-22 17:56:06

回答

2

您可以模拟所需的行为通过fileinput模块,但要记住它会创建一个备份c在后台原来的10GB +文件的OPY:

#! /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触发魔法。

+1

使用'fileinput.input(... inplace = True)'是我接近它的方式+1 – 2013-02-22 18:52:39

+0

亲爱的@crayzeewulf和Jon感谢您的支持。我正在使用其他解决方案(逐行),但是我收到一条错误消息(请参阅上面的更新) – 2013-02-22 18:57:15

+0

@Gianni,我想你可能在输入文件的某一行有超过三个条目。错误消息('ValueError:解包太多的值)可能在行上:'x,y,z = line.split()'。我已经更新了上面的示例代码,仅处理具有三列的行。这可能对你并不理想,但你可以很容易地修改'if'语句来满足你的需求。 – crayzeewulf 2013-02-22 21:21:30