Please, I want to find the squares of the numbers stored in the .txt file named 'myNumbers.txt'

myNumbers.txt

2
3
4
5
3

I have these python script:

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

     f_in.close()

I tried this and it is working very well, but I want to know if there is an other way.

有帮助吗?

解决方案

Always use the with statement for handling files. And no there's need to use str.strip here, as float will take care of the white-spaces:

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

From 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 with white-spaces:

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

其他提示

[float(a)**2 for a in open("C:/Users/vjaiswa5/Downloads/a.txt", "r").read().split()]

Returns an array of squared numbers.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top