Lines in files | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Lines in files

How can I know the number of line in txt file and read it line by line?

17th Nov 2018, 10:12 AM
Student
Student  - avatar
3 Answers
+ 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))
17th Nov 2018, 5:59 PM
Abdou
+ 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.)
17th Nov 2018, 12:56 PM
HonFu
HonFu - avatar
+ 1
Abdesslam Dai readlines returns an itribal object which u can git the length of by saying len(f.readlines)
18th Nov 2018, 7:14 AM
jay