+ 3
Lines in files
How can I know the number of line in txt file and read it line by line?
3 ответов
+ 3
You can do that using the 'readlines()' method to read all the lines from the file.
example:
f = open('example.txt', 'r')
lines = f.readlines()
for line in lines:
print(line)
In order to get the number of lines in the file you can make a list and append the lines to it, then get the length lf the list.
example:
f = open('example.txt', 'r')
lines = f.readlines()
lines_list = []
for line in lines:
lines_list.append(line)
print(len(lines_list))
+ 2
There is the method 'readlines' that puts all the lines in a file in a list.
Then you can treat them separately any way you want or just count them by using len on the list.
(This assumes that every line is ended with a newline.)
+ 1
Abdesslam Dai readlines returns an itribal object which u can git the length of by saying len(f.readlines)