我正在使用python中的numpy数组。我想将数组及其属性打印到txt输出。我希望文本输出以空行结束。我怎样才能做到这一点?
我试过了:
# Create a text document of the output
with open("demo_numpy.txt","w") as text:
text.write('\n'.join(map(str, [a,shape,size,itemsize,ndim,dtype])) + '\n')
还有:
# Create a text document of the output
with open("demo_numpy.txt","w") as text:
text.write('\n'.join(map(str, [a,shape,size,itemsize,ndim,dtype])))
text.write('\n')
但是,当我在GitHub桌面中打开文件时,我仍然得到文件最后一行是" dtype"
的指示答案 0 :(得分:3)
执行"\n".join( ... )
时,您将收到以下表格的字符串:
abc\ndef\nghi\nhjk
- 换句话说,它不会以\n
结尾。
如果您的代码写了另一个\n
,那么您的字符串将采用
abc\ndef\nghi\nhjk\n
但是这并没有在文件的末尾添加一个空行,因为textfiles应该包含以\n
结尾的行。这就是Posix标准所说的。
所以你需要另一个 \n
,这样你文件的最后两行是
hjk\n
\n
如果您要求Python读取缺少最终尾随\n
的文本文件,Python将不会窒息。但它也不会将文本文件中的单个尾随\n
视为空行。得知GitHub同样如此,我也不会感到惊讶。
答案 1 :(得分:-1)
这是使用Python 3.x打印函数解决的,该函数会在每个print语句的末尾自动插入一个新行。
以下是代码:
with open("demo_numpy.txt","w") as text:
print(a, file = text)
text.close()
print
函数而不是.write
更合适。