Python 使用 numpy 将矩阵附加到现有文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17731419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Appending a matrix to an existing file using numpy
提问by user2596825
I'm trying to add a matrix to an existing csv file. Following thislink, I wrote the following code,
我正在尝试将矩阵添加到现有的 csv 文件中。按照这个链接,我写了下面的代码,
f_handle = file(outfile+'.x.betas','a')
np.savetxt(f_handle,dataPoint)
f_handle.close()
where I have imported numpy as np, i.e.
我将 numpy 作为 np 导入的地方,即
import numpy as np
But I get this error:
但我收到此错误:
f_handle = file(outfile+'.x.betas','a')
TypeError: 'str' object is not callable
f_handle = file(outfile+'.x.betas','a')
TypeError: 'str' 对象不可调用
I can't figure out what the problem seems to be. Please help :)
我无法弄清楚问题似乎是什么。请帮忙 :)
回答by Bitwise
Change file()
to open()
, that should solve it.
更改file()
到open()
,应该解决这个问题。
回答by unutbu
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
字符串的变量。Python然后抱怨str
对象在遇到时不可调用
file(...)
You can avoid the issue by, as Bitwise says, changing file
to open
.
正如 Bitwise 所说,您可以通过更改file
为open
.
You could also avoid the problem by not naming a variable file
.
您还可以通过不命名变量来避免该问题file
。
Nowadays, the best way to open a file is by using a with
-statement:
如今,打开文件的最佳方式是使用with
-statement:
with open(outfile+'.x.betas','a') as f_handle:
np.savetxt(f_handle,dataPoint)
This guarantees that the file is closed when Python leaves the with
-suite.
这保证了当 Python 离开with
-suite时文件被关闭。