
Specific Built-in Types
|
29
Operations
All sequence operations (see Table 3, earlier in this book).
Files
The built-in open function creates a stdio file object, the most
common file interface. File objects export the method calls in
the next section. In recent releases, the type name
file can
be used as a synonym for
open when creating a file object
(but
open is the generally recommended spelling).
Also see the
open function in the section “Built-in Func-
tions,” later in this book; the
anydbm, shelve, and pickle
modules in the section “Object Persistence Modules,” later in
this book; the
os module descriptor-based file functions and
the
os.path directory path tools in the section “The os Sys-
tem Module,” later in this book; and the Python SQL data-
base API in the section “Python Portable SQL Database
API,” later in this book.
Input files
infile = open('data.txt', 'r')
Creates input file ('r' means read as text, while 'rb'
reads binary with no line-break translation). The file-
name string (e.g.,
'data.txt') maps to the current work-
ing directory, unless it includes a directory path prefix
(e.g.,
'c:\\dir\\data.txt'). The mode argument (e.g.,
'r') is optional and defaults to 'r'.
infile.read()
Reads entire file, returning its contents as a single string.
In text mode (
'r'), line-ends are translated to '\n'.In
binary mode (
'rb'), the result string can contain non-
printable characters (e.g.,
'\0').
infile.read(N)