如何使用Python将控制台输出放入.csv?

时间:2013-06-30 11:46:00

标签: python numpy output

我想将小波系数从控制台放到.csv行。

以下代码只能将一个数字放入.csv文件

   def waveletdbbiorone(self):     #function for Wavelets computation
     for filename in glob.iglob ('*.tif'):
     imgwbior = mahotas.imread (filename) #read the image
     arraywbior = numpy.array([imgwbior])#make an array for pywt module
     coefwbior = pywt.wavedec(arraywbior,'db1')#compute wavelet coefficients
     arr = numpy.array([coefwbior])
     np.set_printoptions(threshold=3)
     # print arr
  for elem in arr.flat[:50]:
    #print('{}\t'.format(elem))  #this code puts the result to console
    with open('сomput.csv', 'wb') as csvfile:
      writer = csv.writer(csvfile, delimiter=' ', quotechar='|',    quoting=csv.QUOTE_MINIMAL)
      writer.writerow([('{}\t'.format(elem))])

谢谢

1 个答案:

答案 0 :(得分:2)

我认为问题是您始终使用w(写入模式)打开文件,这会自动删除 内容:

试试这个:

 with open('сomput.csv', 'wb') as csvfile:
     for elem in arr.flat[:50]:
        #print('{}\t'.format(elem))  #this code puts the result to console

         writer = csv.writer(csvfile, delimiter=' ', quotechar='|',    quoting=csv.QUOTE_MINIMAL)
         writer.writerow([('{}\t'.format(elem))])

另外一个添加,保存数组的首选方法:

numpy.savetxt("foo.csv", array, delimiter=" ")

和扁平化也有效:

numpy.savetxt("foo.csv", array.flat[:50], delimiter=" ")