Skip to main content
 首页 » 编程设计

python打开一个包含整数的文件

2024年09月07日10Renyi-Fan

python 新手,有人可以告诉我为什么下面的代码会抛出错误吗?并建议我修复

def cel_to_fahr(c): 
     if c < -273.15: 
         return "physical matter can reach only till -273.15" 
     else: 
         f = c * 9/5 + 32 
         return f 
 
temp = open("tempr.txt") 
tempr = temp.read() 
tempr = tempr.splitlines() 
 
for t in tempr: 
    print(cel_to_fahr(t)) 

文件内容:

10 
-20 
-289 
100 

错误:

Traceback (most recent call last): 
  File "cel_to_fahr.py", line 41, in <module> 
    print(cel_to_fahr(t)) 
  File "cel_to_fahr.py", line 29, in cel_to_fahr 
    if c < -273.15: 
TypeError: '<' not supported between instances of 'str' and 'float' 

请您参考如下方法:

这是非常基础的 python。您可以阅读有关写入和读取文件的更多信息。 Python 中的一个常见做法是使用 with...open。这将确保您之后关闭文件。考虑这个例子(有效) with with... open。它还将创建文件。

with open('tempr.txt','w') as f: 
    f.write('10\n-20\n-289\n100') 
 
def cel_to_fahr(c): 
    if c < -273.15: 
        return "physical matter can reach only till -273.15" 
    else: 
        return c * 9/5 + 32 
 
with open('tempr.txt') as f: 
    tempr = [float(i) for i in f.read().split('\n')] 
 
for t in tempr: 
    print(cel_to_fahr(t))