我想從輸入文件中讀取所有列,並只將選定的列打印到輸出文件(第0,第3和第2列),並保留標題(4
和Temperature = 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
你需要數字是一個float/int嗎?爲什麼不把它作爲一個字符串 –
這沒關係。我可以把它們保存爲一個字符串。 – erhan
所以不要將它轉換爲一個浮動,它不會改變值...保持它作爲一個字符串:) –