files so when we look at the lines in filewe need to imagine that there is special invisible character called the newline at the end of each line that marks the end of the line so the newline character separates the characters in the file into lines reading files while the file handle does not contain the data for the fileit is quite easy to construct for loop to read through and count each of the lines in filefhand open('mbox-short txt'count for line in fhandcount count print('line count:'countcodewe can use the file handle as the sequence in our for loop our for loop simply counts the number of lines in the file and prints them out the rough translation of the for loop into english is"for each line in the file represented by the file handleadd one to the count variable the reason that the open function does not read the entire file is that the file might be quite large with many gigabytes of data the open statement takes the same amount of time regardless of the size of the file the for loop actually causes the data to be read from the file when the file is read using for loop in this mannerpython takes care of splitting the data in the file into separate lines using the newline character python reads each line through the newline and includes the newline as the last character in the line variable for each iteration of the for loop because the for loop reads the data one line at timeit can efficiently read and count the lines in very large files without running out of main memory to store the data the above program can count the lines in any size file using very little memory since each line is readcountedand then discarded if you know the file is relatively small compared to the size of your main memoryyou can read the whole file into one string using the read method on the file handle fhand open('mbox-short txt'inp fhand read(print(len(inp) print(inp[: ]from stephen marquar in this examplethe entire contents (all , charactersof the file mbox-short txt are read directly into the variable inp we use string slicing to print out the first characters of the string data stored in inp