2016-09-20 84 views
0

我想知道爲什麼我的代碼不工作。我想在小數點後用2個數字來舍入兩列數據。我下面就在這時下面的代碼:Python - 格式化ascii表的數字

from __future__ import print_function 

with open('input.dat', 'r') as f, open('output.txt', 'w') as outfile: 
    for line in f: 
     try: 
      line = line.strip() 
      columns = line.split() 
      vx = float(columns[0]) 
      vy = float(columns[1]) 
      print("{:.2f\t}".format(vx),"{:.2f}".format(vy), file=outfile) 
     except ValueError: 
      print(line, file=outfile) 

輸入數據就像下面

XY 
HH 
M&M 
TS 
1.83746 2.12131 
1.12121 1.89942 
1.32435 1.99443 
1.65392 2.00001 
1.48732 2.21773 
... 
... 

輸出應該像下面:

XY 
HH 
M&M 
TS 
1.84 2.12 
1.12 1.90 
1.32 1.99 
1.65 2.00 
1.49 2.22 
... 
... 

回答

3

我覺得這條線是錯誤的

print("{:.2f\t}".format(vx),"{:.2f}".format(vy), file=outfile) 

該標籤應該在{}之外,我會這樣改寫它

print("{:.2f}\t{:.2f}".format(vx, vy), file=outfile)