python读取一个文件,为每一行保存一个新的广告保存同一个文件

时间:2013-02-22 17:36:12

标签: python performance save overwrite

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

1 个答案:

答案 0 :(得分: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的{​​{1}}参数会触发魔法。