2016-07-19 85 views
0

我真的很陌生,我無法做一些非常簡單的事情。我在這裏看到了一些用於處理字符串和數字的例子,但不知道如何處理幾行後跟數組數組的一個字符串頭。我找到了一個部分解決方案,但是第一行數據被部分截斷。這是我所做的:閱讀/書寫標題字符串和數字數組

import numpy as np 
infil="infile.txt" 
outfil="outfile.txt" 
fi = open(infil,"r") 
fo = open(outfil,"w") 
lines = fi.readlines() 
fo.writelines(lines[0:3]) 
fi.close() 
x1, x2, x3, x4, x5, x6, x7 = np.loadtxt(infil, skiprows=3, unpack=True) 
# Some computations with those columns of numbers occurs here. 
data = np.array([x1,x2,x3,x4,x5,x6,x7] 
data = data.T 
np.savetxt(outfil, data, fmt='%f') 
fo.close()  

以上幾乎都有效。這只是 第一行數據的前半部分丟失。

任何幫助將不勝感激。

感謝,

+0

你還應該包括infile.txt'的'一個片段,使我們可以看到的數據是什麼樣子。 – jme

+0

好點。我介紹下面的示例行。我用\ n來表示輸入文件中的新行。 //線的數目: // v 1215 \ N:512.0 \ n X1 X2 X3 X4 X5 X4 6 X 7 \ n 73156.727567363 \t \t 23982.109 0.000000000 \t \t 0.0 -0.0009 \t \t 31.353455648 128.485 \ n 73188.081023010 \t 23863.683 \t \t 0.000000000 0.0 \t \t -0.0006 31.303370255 \t 128.225 \ n 73219.334307873 \t \t 23745.635 0.000000000 \t \t 0.0 -0.0008 \t 31.303370255 \t 128.170 \ n 73250.687763521 \t 23627.209 \t 0.000000000 \t 0.0 \t -0.0006 \t 31.303370255 \t 128.115 \ n –

回答

0

我想添加一個也許更完美的解決方案: np.savetxt接受被寫入之前的數據文件頭字符串。有了這個,你真的不需要那麼臨時文件:

np.savetxt(filename, data, header="my header\nand a second line")

+0

謝謝!是的,這確實有道理,savetxt會有這種選擇。一個更優雅的解決方案正在等待着...... –

+0

好吧,我終於嘗試瞭解你所建議的解決方案。它會創建一個標題,其中每行以「#」開頭,​​並且還有一個額外的空白行(前面加上「#」)。我不想要這些。所以我的三行標題需要寫出如下:np.savetxt(outfil,data,fmt ='%f \ t',header = h1 + h2 + h3.rstrip('\ n'),comments = '')寫出我想要的標題,緊接着是數據行。再次感謝你的幫助。 –

+0

好的,我沒有意識到你不想標題被標記。如果它適合你,你可能想考慮將我的答案標爲已接受的答案 – Dux

0

比爾是的!解決了!雖然解決方案是INelegant。問題在於輸出文件在3行標題之後有許多行格式正確的數據。前面的算法切斷了前1.5行數據。我在下面給出的解決方案確實有效,但它並不優雅,因爲我使用臨時文件將格式化的數據行傳遞給我寫入最終輸出文件的字符串。任何關於改進和改進這個算法的建議都會被讚賞。直到那時,這工作得很好。

import numpy as np    # Load useful routines for arrays. 

infil="infile.txt"    # Input file name. 
tfil ="tmp.txt"     # Temporary file name. 
outfil="outfile.txt"   # Output file name. 

fi = open(infil,"r")   # Open input file. 
ft = open(tfil,"w")    # Open temporary file for writing into. 
fo = open(outfil,"w")   # Open output file. 

lines = fi.readlines()   # Read in the input file. 

fi.close()      # Close input file. 




x1, x2, x3, x4, x5, x6, x7 = np.loadtxt(infil, skiprows=3, unpack=True) 
          # Read in and unpack the numerical arrays from the input file. 

# Computation with those numerical arrays will occur here when I'm ready.        


data = np.array([x1,x2,x3,x4,x5,x6,x7]) 
          # Pack the data arrays together. 

data = data.T     # Transpose the data into columns. 


np.savetxt(tfil, data, fmt='%f\t')  # Write to temporary file. 


ft.close()      # Close temporary file. 

ft = open(tfil,"r")    # Now open temporary file to read in the formatted data lines. 

dlines = ft.readlines()   # Read in the temporary file. 

fo.writelines(lines[0:3])  # Write the header to the output file. 

fo.writelines(dlines)   # Write the formatted data lines to the output file. 

fo.close()      # Close output file.