2015-06-08 84 views
0

我想從輸入文件中讀取所有列,並只將選定的列打印到輸出文件(第0,第3和第2列),並保留標題(4Temperature = 298 K)。使用Python將所選列從一個文件複製到另一個文件

我的當前代碼寫入「[1.0,1.0]」輸出文件。我該如何解決它?

#!/usr/bin/python 

with open("test.txt", "r") as f: 
    a1=[] 
    a2=[] 
    a3=[] 
    a4=[] 
    for line in f: 
     if not line.strip() or line.startswith('Temperature') or line.startswith('4'): continue 
     row = line.split() 
     a1.append(str(row[0])) 
     a2.append(float(row[1])) 
     a3.append(float(row[2])) 
     a4.append(float(row[3])) 
f = open('output.txt','a') 
f.write(str(a1)+str(a3)+str(a2)) 
f.close() 

輸入文件:

4 
Temperature = 298 K 
C -5.27210 0.23153 0.13488 
H -1.99335 -2.87058 3.25594 
H -1.33502 -3.88407 1.93295 
H -3.06617 -3.39783 1.91314 

請求的輸出:

4 
Temperature = 298 K 
C 0.13488 0.23153  
H 3.25594 -2.87058  
H 1.93295 -3.88407 
H 1.91314 -3.39783 
+0

你需要數字是一個float/int嗎?爲什麼不把它作爲一個字符串 –

+0

這沒關係。我可以把它們保存爲一個字符串。 – erhan

+1

所以不要將它轉換爲一個浮動,它不會改變值...保持它作爲一個字符串:) –

回答

1

那怎麼樣?

with open('data.txt', 'r') as fin: 
    with open('data2.txt', 'w') as fout: 
     # Header 
     fout.write(fin.readline()) 
     fout.write(fin.readline()) 
     # Columns 
     for l in fin: 
      cols = l.split() 
      fout.write("%s % f % f\n" % (cols[0], float(cols[3]), float(cols[2]))) 

該代碼一次只存儲一行文件並立即寫入輸出文件。此外,間距將保留在原始文件中。

+0

它的工作原理,但我應該保持列之間的空間。我怎樣才能做到這一點? – erhan

+0

請參閱我的編輯。 –

2

我不太明白你爲什麼使用有四個不同的列表...你可以做它只有一個容器,像這樣(未測試):

#!/usr/bin/python 

newlines = [] 
with open("test.txt", "r") as f: 
    for line in f: 
     if not line.strip() or line.startswith('Temperature') or line.startswith('4'): continue 
     row = line.split() 
     newlines.append(' '.join([row[0], row[3], row[2]])) 

f = open('output.txt','a') 
f.write('\n'.join(newlines)) 
f.close() 
+0

它給這個錯誤:文件「text.py」,第10行,在 newlines.append(''.join ([row [0],row [3],row [2]]))IndexError:列表索引超出範圍。 – erhan

+0

因爲您使用的是與您在問題中發佈的文件不同的文件。 –

相關問題