- 1
What is the output of print(sum(1 for line in open("filename.txt"))) ?
It exactly gives the number of lines present in the file. I don't know how it works. Can anyone help me...
5 Answers
+ 2
well, that's an approximate explanation ^^
no tuple used here, but list comprehension syntax wich makes a generator passed as argument to sum() function...
the list comprehension iterate over the opened file wich give each lines in it, and return 1 for each line, so sum of 1 times number of lines in file give total number of lines ^^
open() doesn't "return a list of lines in a file", but return a file object that will be iterated line by line...
to get a list of lines in a file, you should use readlines() function on it:
lineslist = open("filename.txt").readlines()
so you could get total number of lines in a file by doing:
print(len(open("filename.txt").readlines()))
+ 1
Pardha Saradhi
Here, you seeing tuple comprehension.
open() function has used to open a file.
So,this code open a file and every line of a file 'for' adds one to the tuple.
So,
It looks like this,
sum(1,1,1,1....) #Here 1 means one line
And , sum() function has calculate sum of all ones (lines).
+ 1
Ëâ*°â˘.Ëâ*°⢠Mohan 333 â˘Â°*âË.â˘Â°*âË
How 1 is added as tuple by using for loop ? Why don't it take each character instead of each line in the file ?
+ 1
Pardha Saradhi
Tuple comprehension syntax:
(Expression for counter_variable in iterators (strings,lists,tuples,etc))
In this code we didn't add any expressions just adding 1 only to a tuple.
List comprehensions are also same as a tuple
comprehension. So, have a look on this lesson,
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2454/
https://www.sololearn.com/learn/Python/2446/
"""
Python has automatically read a file line by line. And open() function return a list of lines in a file.
"""