python读取文件,为每个订单广告保存一个新列,并保存相同的文件 [英] python read a file, save a new column for each line ad save the same file

查看:74
本文介绍了python读取文件,为每个订单广告保存一个新列,并保存相同的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个x,y,z值的文件.我希望找到一种优雅的方法来打开并向每行添加新的值id,然后再次保存相同的文件.

I have a file with x,y,z values. I wish to find an elegant way to open and add a new value id to each line and save again the same file.

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)

ex

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中阅读几种方法,并测试了几种方法.老实说,我已经尝试过并无法保存新文件.

i am reading in Stackoverflow several approach and i tested several approaches. i am honest to say that i have tried and failed to save the new file.

我尝试了Followig解决方案

i had tried the followig solution

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

新元素(真实数据)所在的位置

where newelement (real data) is

'481499.55 6244324.75 19.15 (377, 2909)\n' 

推荐答案

您可以通过

You can emulate the required behavior via the fileinput module but bear in mind that it will create a backup copy of your original 10GB+ file in the background:

#! /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)

传递给fileinput.inputinplace参数触发魔术.

The inplace parameter passed to fileinput.input triggers the magic.

这篇关于python读取文件,为每个订单广告保存一个新列,并保存相同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆