只是询问是否有可能的代码或方法来计算文本文件中的整行。 例如,我有以下文本文件;
Force Displacement Theta
0 0 0
15 0 0
3 0.15 0
1 1 90
-3 0.15 0
我想使用方程逐行计算这些数字的 WorkDone
W = Force * Displacement * cos(Theta)
我已经尝试过了;
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)
我不知道我做了什么,所以请帮忙
最佳答案
如果我是你,我会创建一个用于解析的函数 (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 之前打开它。 ..
block :
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))
这应该或多或少可以达到目的。
关于python - 如何计算文本文件中的一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43819774/