2017-05-06 74 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)) 

这或多或少会做招。