1. Count lines of text
The most common is readlines.
>>> handler=open (' input_file.txt ') >>> lines=handler.readlines () >>> Lenoffile=len (lines )
However, if it is a text file more than 100m, the above method is basically determined to be very slow, even can not run
So, we need other ways.
1) using cycle count, introduce enumerate method
Note: Count is starting from-1
2) If we consider the problem of performance, we use other methods
Because text files are generally n/a newline characters, we can load part of the text and calculate how many line breaks are inside.
>>> Import codecs>>> count = 0>>> the_file = Codecs.open (' input_file.txt ', ' RB ', ' Utf-8 ') > >> Try:while (True): buffer = the_file.read (8192*1024) if not buffer:break
2. Read a line (take small text for example)
We usually think of loops and then go to a line to stop and print
The above example can be encapsulated as a method:
But we have a much quicker approach:
We introduce Linecache, we get a line by Getline method, but we need to note: its number of rows is starting from 0
Right here, thank you.
------------------------------------------------------------------
Click to jump 0 basic python-Catalogue
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Easy Python file feature-operations on Rows