python读取文件,为每一行保存一个新列并保存相同的文件

标签 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' 

最佳答案

您可以通过 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)

传递给 fileinput.inputinplace 参数会触发魔法。

关于python读取文件,为每一行保存一个新列并保存相同的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15030038/

相关文章:

mysql 查询速度太慢

windows - TortoiseSVN 在某些 Windows 配置上非常慢

java - 在android studio的本地存储中保存小串数据

java - 在这种情况下保存响应集的更好方法是什么?

php - 如何在 PHP 中创建网页图像?

python - 使用引导 random.choice

python - cvxpy/ecos pip安装报错

python - 使用两个字典映射列

.net - 一个 110 kb 的 .NET 4.0 应用程序需要 10 秒的冷启动时间,这是 Not Acceptable !

python - 如何定义在使用 nosetest 进行测试期间只调用一次的设置方法?