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.
This is an example text in an example file.
It even has
several
lines.
1 f = file( "example.txt", "r")
2 for line in f.readlines():
3 print line
4 f.close()
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.
This is an example text in an example file.
It even has
several
lines.
1 f = file( "example.txt", "r")
2 for line in f:
3 print line
4 f.close()
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í
-
Modify the program so that it does not print the extra empty lines.
-
Modify the program so that it prints a line number at the beginning of each line.
-
Modify the program so that it prints the number of characters in the line at the beginning of each line.