Page 143 - PYTHON-12
P. 143

Explanation:


               In the above program, a special type of object is created to access the CSV file (reader object), which
               is csv_reader using the reader() function. The reader object is an iterable that gives us access to
               each line of the CSV file as a list of fields. The function next() is used to directly point to this list of
               fields to read the next line in the CSV file. .next() method returns the current row and advances the
               iterator to the next row.

               The variable ‘c’ is used as a counter variable to count the number of rows/records present in this
               file, which is finally printed and thus the output is so obtained.
               One of the important observations from the output is the number of records which are being
               displayed as 11 instead of 10. This is so because the header (first line) in the student csv file is also
               treated as a record only. This limitation is overcome in the next implementation.

                 CTM: .next() method returns the current row and advances the iterator to the next row.

               Practical Implementation–8


               Program to count the exact number of records present in the csv file excluding the header.




































           Computer Science with Python–XII  4.14 In the above program we have used line_num object of CSV file. Our csv_reader_object has a method

               called line_num that returns the number of lines in our CSV.

               Then, if statement checks if the line is first line or not. If the condition is true, i.e., if it is the header
               line, then it is ignored using continue statement and the counting of records is resumed from
               second line onwards. Also, line_num object always stores the current line in consideration and,
               hence, the correct output for 10 records is so obtained.

                 CTM: line_num is nothing but a counter which returns the number of rows which have been iterated.
   138   139   140   141   142   143   144   145   146   147   148