Skip to main content
 首页 » 编程设计

python之在 .txt 中查找数字的平方

2025年05月04日15mfryf

拜托,我想找到存储在名为“myNumbers.txt”的 .txt 文件中的数字的平方

我的号码.txt

2 
3 
4 
5 
3 

我有这些 python 脚本:

if __name__=="__main__": 
     f_in=open("myNumbers.txt", "r")      
     for line in f_in:                   
          line=line.rstrip() 
          print float(line)**2 
 
     f_in.close() 

我试过了,效果很好,但我想知道是否有其他方法。

请您参考如下方法:

始终使用with 语句 来处理文件。不需要在这里使用 str.strip,因为 float 会处理空白:

with open("mynumbers.txt") as f_in: 
    for line in f_in:                   
        print float(line)**2 

来自 docs :

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

float 带空格:

>>> float('1.2\n') 
1.2 
>>> float('  1.2  \n') 
1.2