在.txt中查找数字的平方

use*_*042 1 python file gedit

请,我想找到存储在名为'myNumbers.txt'的.txt文件中的数字的方块

myNumbers.txt

2
3
4
5
3
Run Code Online (Sandbox Code Playgroud)

我有这些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()
Run Code Online (Sandbox Code Playgroud)

我尝试了这个并且它工作得非常好,但我想知道是否还有其他方法.

Ash*_*ary 5

始终使用with statement处理文件.并且不需要在str.strip这里使用,因为float将照顾白色空间:

with open("mynumbers.txt") as f_in:
    for line in f_in:                  
        print float(line)**2
Run Code Online (Sandbox Code Playgroud)

来自docs:

在处理文件对象时,最好使用with关键字.这样做的好处是文件在套件完成后正确关闭,即使在途中引发了异常.

float 白色空格:

>>> float('1.2\n')
1.2
>>> float('  1.2  \n')
1.2
Run Code Online (Sandbox Code Playgroud)