簡體   English   中英

如何使用Python將控制台輸出放入.csv?

[英]How to put console output into .csv using Python?

我想將小波系數從控制台放到.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))])

謝謝

我認為問題是你總是用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=" ")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM