2016-11-11 159 views
1

我真的很新的python。 我想從txt文件中讀取數據,並從中選擇一些列和行,然後將其寫入新的txt文件。如何從txt文件中專門選擇列和行,並用python將其寫在另一個txt文件中?

這是我的輸入數據的例子:

*ELEMENT_SOLID 
$# eid  pid  n1  n2  n3  n4  n5  n6  n7  n8 
     1  1 2235 2237 1579 1565 2067 2067  596  596 
     2  1 2238 2240 1525 1547 2073 2073  674  674 

我只需要使用第3和第4行,我不需要第三科拉姆。

我已經從許多回答的問題看過,但我仍然沒有弄清楚如何解決這個問題。

我希望你能幫我解決我的問題。

謝謝!

回答

0

該代碼從文件'element_solid.dat'中讀取tabluar,並在其更改一個元素後將其保存到'element_solid2.dat'中。

如果你想只保存陣列的一部分,試用命令 np.savetxt('element_solid2.dat',data[0:1,3:6], fmt='%7.i')

import numpy as np 

#Main programm 
#read array from file 'element_solid.dat' 
data = np.loadtxt('element_solid.dat', skiprows=2) 
print(data) 

#change one number in data to see the difference 
data[0,2]=0 

#save array to file 'element_solid.dat' without header 
np.savetxt('element_solid2.dat',data, fmt='%7.i') 

在下面我將scatch 的其他解決方案(如在意見中的要求),這是更靈活的,但需要更多的微調:

with open(filename) as fil: 
    for line in fil: 
     if line=="\n": 
      #skip empty line 
      continue 
     if line[0]=='#': 
      #skip comment lines starting with # 
      continue 
     if line=="#LastLine": 
      #stops searching the file when reaches this line 
      break 
     else: 
      #play around with line.split() -> string to list 
      #and fltList=[float(elem) for elem in line.split()] 
      #fltList is a list of floatingpoint numbers 
+0

非常感謝你Dutscke先生爲您的答案!這真的很有幫助。 我可以問一個後續問題嗎? 如果在數據列表之後會出現幾行不需要的句子,然後再次輸入另一個重要數據。 簡而言之,我需要再跳過幾行然後讀取另一個數據。我怎樣才能做到這一點? –

+1

馬斯杜基先生,如果你喜歡我的回答,請投票支持;) –

相關問題