使用numpy将矩阵附加到现有文件 [英] Appending a matrix to an existing file using numpy

查看:122
本文介绍了使用numpy将矩阵附加到现有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将矩阵添加到现有的csv文件中. 在链接之后,我编写了以下代码,

I'm trying to add a matrix to an existing csv file. Following this link, I wrote the following code,

f_handle = file(outfile+'.x.betas','a')
np.savetxt(f_handle,dataPoint)
f_handle.close()

我将numpy导入为np,即

where I have imported numpy as np, i.e.

import numpy as np

但是我得到这个错误:

f_handle = file(outfile +'.x.betas','a')
TypeError:"str"对象不可调用

f_handle = file(outfile+'.x.betas','a')
TypeError: 'str' object is not callable

我不知道问题出在哪里. 请帮忙:)

I can't figure out what the problem seems to be. Please help :)

推荐答案

似乎您已经定义了一个名为file的变量,它是一个字符串.然后,Python抱怨str对象在遇到时无法调用

It looks like you might have defined a variable named file which is a string. Python then complains that str objects are not callable when it encounters

file(...)

如Bitwise所述,可以通过将file更改为open来避免此问题.

You can avoid the issue by, as Bitwise says, changing file to open.

您也可以通过不命名变量file来避免此问题.

You could also avoid the problem by not naming a variable file.

如今,打开文件的最佳方法是使用 with -statement :

Nowadays, the best way to open a file is by using a with-statement:

with open(outfile+'.x.betas','a') as f_handle:
    np.savetxt(f_handle,dataPoint)

这可确保在Python离开with -suite时关闭文件.

This guarantees that the file is closed when Python leaves the with-suite.

这篇关于使用numpy将矩阵附加到现有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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