2017-05-06 73 views
1

只是詢問是否有可能的代碼或方法來計算文本文件中的整行。 例如,我有以下文本文件;如何從文本文件中計算一行?

Force Displacement Theta 
0  0    0 
15  0    0 
3  0.15   0 
1  1    90 
-3  0.15   0 

我想用它來計算由線這些數字線WorkDone

W =力×位移* COS

我已經試過(西塔);

fname = input("Please enter the filename: ") 
infile = open(fname, "r") 

with open(fname, 'r'): 
    data = infile.readline() 
    f,D,Theta = eval(data) 
    display = f * D * cos(radians(Theta)) 
    output.setText(("%,2f") % display) 

我不知道我這樣做了,請幫助

+0

循環在哪裏?您只獲取文件的第一行。 – dede

+0

不要擔心這一點。我只想知道是否有可能的代碼來做到這一點。 – Donkey

+0

你的意思是:計算輸入文本文件每一行的結果? – xtofl

回答

2

如果我是你,我會創造瞭解析(parse)的函數,用於計算(work)的功能。

def parse(line): 
    return (float(token) for token in line.split()) 

def work(f, d, theta): 
    return f * d * cos(theta) 

中的一些問題:打開的文件應該有一個名字:with open(...) _as infile_: ...你沒有with...塊之前將其打開:

fname = input("...") 
with open(fname, 'r') as infile: 
    infile.readline() # drop the first line 
    for line in infile: 
     f, d, t = parse(line) 
     print(work(f, d, t)) 

這或多或少會做招。