• Register
1 vote
13 views

Problem:

Well, I have a text file containing thousands of lines possibly. I am willing to give them a count (if possible). What is the easiest and efficient way to write a program to get number of lines in a file python? Please, keep it simple so that I can understand the code easily.
Thanks.

12 7 7
15,250 points

1 Answer

1 vote

Solution:

Yes, you can easily read a text file and count the line from it by using the .split() function and a for-loop.

Check the code snippet below:

file = open("work.txt","r") 
Count = 0  
Content = file.read() 
LineList = Content.split("\n") 
  
for n in LineList: 
    if n: 
        Count += 1          
print("This is the number of lines in the file") 
print(Count) 

This should help you. Thanks.

13 9 6
94,240 points

Related questions

1 vote
1 answer 20 views
20 views
Problem: I have a python file that contains too many lines of code. I have written a code to count the total number of lines in a exact file. My code: def file_name(fname): with open(fname) as fn: for i, l in enumerate(fn): pass return i+1 Does the code give me the exact count ? If not how can I solve this?
asked Apr 5 LizzyM 6.1k points
1 vote
1 answer 24 views
24 views
Problem: I am a new student of c++ and learning new things day by day. Well, I have a text file containing thousands of lines possibly. I am willing to give them a count (if possible). What is the easiest and efficient way to get number of lines in a file c++? Please, keep it simple so that I can understand the code easily. Thanks.
asked Mar 29 Gavin 15.3k points
0 votes
1 answer 21 views
21 views
I have a python file that contains too many lines of code. I have written a code to count the total number of lines in a exact file (Don’t have any idea if it works). My code: def file_name(fname): with open(fname) as fn: for i, l in enumerate(fn): pass return i+1 Does the code give me the exact count ?
asked Mar 10 LizzyM 6.1k points
0 votes
1 answer 19 views
19 views
Problem: Hello kodlogs, Recently while attempting, the problem in the python there is a error that came can you please help sort out this problem, How can I get the first character from the first string in Python?,It seems that I could use list[0][1:] but that does not give me the first character of the string that I am looking for. mysrt = "sdf" >>> mystr[0][1:]
asked Jun 6 Gavin 15.3k points
1 vote
1 answer 10 views
10 views
Problem: Hello Kodlogers, I have started learning Java programming recently. I am solving problems from many websites and even textbooks. Right now I got a problem that says to get numbers of lines in a file using java program. I don’t know how to solve this ... . So, it would be better if you can solve the problem and attach the code for my better understanding. Thanks for your concern.
asked Apr 7 Gavin 15.3k points