Python-Ref > Using files > Reading and writing files > Reading a file line by line
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Reading a file line by line

How to read the content of a file one line at a time.
For structured text file, such as unix config files etc., it is often desirable to read a file line-by-line. To do this, we have two very similar ways.
The first one is to use the method readlines of a file object.
Expand/Shrink
This is an example text in an example file.
It even has
several
lines.
Zdroj: (fileio2.py)
  1   f = file( "example.txt", "r")  # we open the file "example.txt" for "r"eading
  2   for line in f.readlines():     # we read all lines into a list and iterate over it
  3       print line
  4   f.close()                      # we close the file
stdout:
This is an example text in an example file.

It even has

several

lines.

Doba běhu: 21.0 ms
The output has some extra empty lines, this is because newline characters are part of each line and the print command adds one new line more.
The second way requires python version 2.3 or newer (not a problem today). From this version of python it is possible to iterate over a file the same way as over a list.
Expand/Shrink
This is an example text in an example file.
It even has
several
lines.
Zdroj: (fileio3.py)
  1   f = file( "example.txt", "r")  # we open the file "example.txt" for "r"eading
  2   for line in f:                 # we iterate over the files lines
  3       print line
  4   f.close()                      # we close the file
stdout:
This is an example text in an example file.

It even has

several

lines.

Doba běhu: 21.3 ms
This approach has the advantage that the lines are read from the file as requested. This is different from the readlines method that reads all the lines at once and then returns them as a list. This difference starts to be important once bigger files are processed, especially if the program stops before processing all of the lines.

Cvičení

  1. Modify the program so that it does not print the extra empty lines.
  2. Modify the program so that it prints a line number at the beginning of each line.
  3. Modify the program so that it prints the number of characters in the line at the beginning of each line.