python - 如何计算文本文件中的一行?

标签 python

只是询问是否有可能的代码或方法来计算文本文件中的整行。 例如,我有以下文本文件;

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/

相关文章:

free pascal 中的 Python+Numpy 模块

python - OpenAi-Gym 具有负值的离散空间

python - Pandas 删除差异未达到阈值的行

python - 在python中检查相同类型的值

python - 如何检查if语句当前时间是否大于时间

c++ - 通过 list 通过 DLL 重定向加载 DLL 文件两次

python - 使用 Google Drive API : Resource has no method "insert' 创建文件夹

python - 我如何使用模拟在 greenlet 中进行测试?

python - 带有无效返回参数的 SWIG、Python、C

python - Tornado 中 "timeout"请求的正确方法