Back to index

python3.2  3.2.2
Classes | Functions | Variables
_pyio Namespace Reference


class  BlockingIOError
class  DocDescriptor
class  OpenWrapper
class  UnsupportedOperation
class  IOBase
class  RawIOBase
class  BufferedIOBase
class  _BufferedIOMixin
class  BytesIO
class  BufferedReader
class  BufferedWriter
class  BufferedRWPair
class  BufferedRandom
class  TextIOBase
class  IncrementalNewlineDecoder
class  TextIOWrapper
class  StringIO


def open



Detailed Description

Python implementation of the io module.

Class Documentation

class _pyio::UnsupportedOperation

Definition at line 251 of file

Function Documentation

def (   file,
  mode = "r",
  buffering = -1,
  encoding = None,
  errors = None,
  newline = None,
  closefd = True 

Definition at line 39 of file

00040          newline=None, closefd=True):
00042     r"""Open file and return a stream.  Raise IOError upon failure.
00044     file is either a text or byte string giving the name (and the path
00045     if the file isn't in the current working directory) of the file to
00046     be opened or an integer file descriptor of the file to be
00047     wrapped. (If a file descriptor is given, it is closed when the
00048     returned I/O object is closed, unless closefd is set to False.)
00050     mode is an optional string that specifies the mode in which the file
00051     is opened. It defaults to 'r' which means open for reading in text
00052     mode.  Other common values are 'w' for writing (truncating the file if
00053     it already exists), and 'a' for appending (which on some Unix systems,
00054     means that all writes append to the end of the file regardless of the
00055     current seek position). In text mode, if encoding is not specified the
00056     encoding used is platform dependent. (For reading and writing raw
00057     bytes use binary mode and leave encoding unspecified.) The available
00058     modes are:
00060     ========= ===============================================================
00061     Character Meaning
00062     --------- ---------------------------------------------------------------
00063     'r'       open for reading (default)
00064     'w'       open for writing, truncating the file first
00065     'a'       open for writing, appending to the end of the file if it exists
00066     'b'       binary mode
00067     't'       text mode (default)
00068     '+'       open a disk file for updating (reading and writing)
00069     'U'       universal newline mode (for backwards compatibility; unneeded
00070               for new code)
00071     ========= ===============================================================
00073     The default mode is 'rt' (open for reading text). For binary random
00074     access, the mode 'w+b' opens and truncates the file to 0 bytes, while
00075     'r+b' opens the file without truncation.
00077     Python distinguishes between files opened in binary and text modes,
00078     even when the underlying operating system doesn't. Files opened in
00079     binary mode (appending 'b' to the mode argument) return contents as
00080     bytes objects without any decoding. In text mode (the default, or when
00081     't' is appended to the mode argument), the contents of the file are
00082     returned as strings, the bytes having been first decoded using a
00083     platform-dependent encoding or using the specified encoding if given.
00085     buffering is an optional integer used to set the buffering policy.
00086     Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
00087     line buffering (only usable in text mode), and an integer > 1 to indicate
00088     the size of a fixed-size chunk buffer.  When no buffering argument is
00089     given, the default buffering policy works as follows:
00091     * Binary files are buffered in fixed-size chunks; the size of the buffer
00092       is chosen using a heuristic trying to determine the underlying device's
00093       "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
00094       On many systems, the buffer will typically be 4096 or 8192 bytes long.
00096     * "Interactive" text files (files for which isatty() returns True)
00097       use line buffering.  Other text files use the policy described above
00098       for binary files.
00100     encoding is the str name of the encoding used to decode or encode the
00101     file. This should only be used in text mode. The default encoding is
00102     platform dependent, but any encoding supported by Python can be
00103     passed.  See the codecs module for the list of supported encodings.
00105     errors is an optional string that specifies how encoding errors are to
00106     be handled---this argument should not be used in binary mode. Pass
00107     'strict' to raise a ValueError exception if there is an encoding error
00108     (the default of None has the same effect), or pass 'ignore' to ignore
00109     errors. (Note that ignoring encoding errors can lead to data loss.)
00110     See the documentation for codecs.register for a list of the permitted
00111     encoding error strings.
00113     newline is a string controlling how universal newlines works (it only
00114     applies to text mode). It can be None, '', '\n', '\r', and '\r\n'.  It works
00115     as follows:
00117     * On input, if newline is None, universal newlines mode is
00118       enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
00119       these are translated into '\n' before being returned to the
00120       caller. If it is '', universal newline mode is enabled, but line
00121       endings are returned to the caller untranslated. If it has any of
00122       the other legal values, input lines are only terminated by the given
00123       string, and the line ending is returned to the caller untranslated.
00125     * On output, if newline is None, any '\n' characters written are
00126       translated to the system default line separator, os.linesep. If
00127       newline is '', no translation takes place. If newline is any of the
00128       other legal values, any '\n' characters written are translated to
00129       the given string.
00131     closedfd is a bool. If closefd is False, the underlying file descriptor will
00132     be kept open when the file is closed. This does not work when a file name is
00133     given and must be True in that case.
00135     open() returns a file object whose type depends on the mode, and
00136     through which the standard file operations such as reading and writing
00137     are performed. When open() is used to open a file in a text mode ('w',
00138     'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
00139     a file in a binary mode, the returned class varies: in read binary
00140     mode, it returns a BufferedReader; in write binary and append binary
00141     modes, it returns a BufferedWriter, and in read/write mode, it returns
00142     a BufferedRandom.
00144     It is also possible to use a string or bytearray as a file for both
00145     reading and writing. For strings StringIO can be used like a file
00146     opened in a text mode, and for bytes a BytesIO can be used like a file
00147     opened in a binary mode.
00148     """
00149     if not isinstance(file, (str, bytes, int)):
00150         raise TypeError("invalid file: %r" % file)
00151     if not isinstance(mode, str):
00152         raise TypeError("invalid mode: %r" % mode)
00153     if not isinstance(buffering, int):
00154         raise TypeError("invalid buffering: %r" % buffering)
00155     if encoding is not None and not isinstance(encoding, str):
00156         raise TypeError("invalid encoding: %r" % encoding)
00157     if errors is not None and not isinstance(errors, str):
00158         raise TypeError("invalid errors: %r" % errors)
00159     modes = set(mode)
00160     if modes - set("arwb+tU") or len(mode) > len(modes):
00161         raise ValueError("invalid mode: %r" % mode)
00162     reading = "r" in modes
00163     writing = "w" in modes
00164     appending = "a" in modes
00165     updating = "+" in modes
00166     text = "t" in modes
00167     binary = "b" in modes
00168     if "U" in modes:
00169         if writing or appending:
00170             raise ValueError("can't use U and writing mode at once")
00171         reading = True
00172     if text and binary:
00173         raise ValueError("can't have text and binary mode at once")
00174     if reading + writing + appending > 1:
00175         raise ValueError("can't have read/write/append mode at once")
00176     if not (reading or writing or appending):
00177         raise ValueError("must have exactly one of read/write/append mode")
00178     if binary and encoding is not None:
00179         raise ValueError("binary mode doesn't take an encoding argument")
00180     if binary and errors is not None:
00181         raise ValueError("binary mode doesn't take an errors argument")
00182     if binary and newline is not None:
00183         raise ValueError("binary mode doesn't take a newline argument")
00184     raw = FileIO(file,
00185                  (reading and "r" or "") +
00186                  (writing and "w" or "") +
00187                  (appending and "a" or "") +
00188                  (updating and "+" or ""),
00189                  closefd)
00190     line_buffering = False
00191     if buffering == 1 or buffering < 0 and raw.isatty():
00192         buffering = -1
00193         line_buffering = True
00194     if buffering < 0:
00195         buffering = DEFAULT_BUFFER_SIZE
00196         try:
00197             bs = os.fstat(raw.fileno()).st_blksize
00198         except (os.error, AttributeError):
00199             pass
00200         else:
00201             if bs > 1:
00202                 buffering = bs
00203     if buffering < 0:
00204         raise ValueError("invalid buffering size")
00205     if buffering == 0:
00206         if binary:
00207             return raw
00208         raise ValueError("can't have unbuffered text I/O")
00209     if updating:
00210         buffer = BufferedRandom(raw, buffering)
00211     elif writing or appending:
00212         buffer = BufferedWriter(raw, buffering)
00213     elif reading:
00214         buffer = BufferedReader(raw, buffering)
00215     else:
00216         raise ValueError("unknown mode: %r" % mode)
00217     if binary:
00218         return buffer
00219     text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
00220     text.mode = mode
00221     return text

Here is the call graph for this function:

Here is the caller graph for this function:

Variable Documentation

Definition at line 20 of file