Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to get the number of lines in a text file [duplicate]

I would like to know if it s possible to know how many lines contains my file text without using a command as :

with open('test.txt') as f:
    text = f.readlines()
    size = len(text)

My file is very huge so it s difficult to use this kind of approach...

like image 357
user3601754 Avatar asked Sep 16 '15 11:09

user3601754


People also ask

How do I find out how many lines a text file has in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list. Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

How do I find duplicates in a text file?

To start your duplicate search, go to File -> Find Duplicates or click the Find Duplicates button on the main toolbar. The Find Duplicates dialog will open, as shown below. The Find Duplicates dialog is intuitive and easy to use. The first step is to specify which folders should be searched for duplicates.


1 Answers

As a Pythonic approach you can count the number of lines using a generator expression within sum function as following:

with open('test.txt') as f:
   count = sum(1 for _ in f)

Note that here the fileobject f is an iterator object that represents an iterator of file's lines.

like image 131
Mazdak Avatar answered Sep 18 '22 06:09

Mazdak