Page 65 - Programming the Raspberry Pi Getting Started with Python
P. 65
When the function readline gets to the last line of the file, it returns an empty string ('').
Otherwise, it returns the contents of the line, including the end-of-line character (\n). If it reads a
blank line that is actually just a gap between lines and not the end of the file, it will return just the
end-of-line character (\n). By the program only reading one line at a time, the memory being used is
only ever equivalent to one full line.
If the file is not broken into convenient lines, you can specify an argument in read that limits the
number of characters read. For example, the following will just read the first 20 characters of a file:
Writing Files
Writing files is almost as simple. When a file is opened, as well as specifying the name of the file to
open, you can also specify the mode in which to open the file. The mode is represented by a character,
and if no mode is specified it is assumed to be r for read. The modes are as follows:
• r (read).
• w (write) Replaces the contents of any existing file with that name.
• a (append) Appends anything to be written onto the end of an existing file.
• r+ Opens the file for both reading and writing (not often used).
To write a file, you open it with a second parameter of ' w', ' a', or ' r+'. Here’s an example:
The File System
Occasionally, you will need to do some file-system-type operations on files (moving them, copying
them, and so on). Python uses Linux to perform these actions, but provides a nice Python-style way of
doing them. Many of these functions are in the shutil (shell utility) package. There’s a number of
subtle variations on the basic copy and move features that deal with file permissions and metadata. In
this section, we just deal with the basic operations. You can refer to the official Python documentation
for any other functions (http://docs.python.org/release/3.l.5/library).
Here’s how to copy a file:
To move a file, either to change its name or move it to a different directory:
This works on directories as well as files. If you want to copy an entire folder—including all its
contents and its content’s contents—you can use the function copytree. The rather dangerous