Opening a file for writing

Let's start working with files by opening a file in write mode. We'll be explicit about using the UTF-8 encoding, because we have no way of knowing what your default encoding is. We'll also use keyword arguments to make things clearer still:

>>> f = open('wasteland.txt', mode='wt', encoding='utf-8')

The first argument is the filename. The mode argument is a string containing letters with different meanings. In this case w means write and t means text.

All mode strings should consist of one of read, write or append mode. This table lists the mode codes along with their meanings in the following format  Code:  Meaning :

 

  •  r: Open file for reading. The stream is positioned at the beginning of the file. This is the default.
  • r+: Open for reading and writing. The stream is positioned at thebeginning of the file.
  •  w: Truncate file to zero length or create file for writing. The stream is positioned at the beginning of the file.
  • w+: Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
  • a: Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening seeks or similar.
  • a+: Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening seeks or similar.

One of the preceding should be combined with a selector from the next table for specifying text or binary mode in the following format Code: Meaning :

  •  t: File contents interpreted as encoded text strings. The bytes in the file will be encoded and decoded according the to the specified text encoding, and universal newline translation will be in effect (unless explicitly disabled). All methods which write and read data from the file accept and return str objects. This is the default.
  •  b: File contents are treated as raw bytes. All methods which write and read data from the file accept and return bytes objects.

Examples of typical mode strings might be wb for write binary or at for append text. Although both parts of the mode code support defaults, we recommend being explicit for the sake of readability.

The exact type of the object returned by open() depends on how the file was opened. This is dynamic typing in action! For most purposes, however, the actual type returned by open() is unimportant. It is sufficient to know that the returned object is a file-like object, and as such we can expect it to support certain attributes and methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset