Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(1120)

Side by Side Diff: Lib/_pyio.py

Issue 12760: Add create mode to open()
Patch Set: Created 1 year, 9 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
OLDNEW
1 """ 1 """
2 Python implementation of the io module. 2 Python implementation of the io module.
3 """ 3 """
4 4
5 import os 5 import os
6 import abc 6 import abc
7 import codecs 7 import codecs
8 import warnings 8 import warnings
9 # Import _thread instead of threading to reduce startup cost 9 # Import _thread instead of threading to reduce startup cost
10 try: 10 try:
(...skipping 30 matching lines...) Expand all
41 r"""Open file and return a stream. Raise IOError upon failure. 41 r"""Open file and return a stream. Raise IOError upon failure.
42 42
43 file is either a text or byte string giving the name (and the path 43 file is either a text or byte string giving the name (and the path
44 if the file isn't in the current working directory) of the file to 44 if the file isn't in the current working directory) of the file to
45 be opened or an integer file descriptor of the file to be 45 be opened or an integer file descriptor of the file to be
46 wrapped. (If a file descriptor is given, it is closed when the 46 wrapped. (If a file descriptor is given, it is closed when the
47 returned I/O object is closed, unless closefd is set to False.) 47 returned I/O object is closed, unless closefd is set to False.)
48 48
49 mode is an optional string that specifies the mode in which the file 49 mode is an optional string that specifies the mode in which the file
50 is opened. It defaults to 'r' which means open for reading in text 50 is opened. It defaults to 'r' which means open for reading in text
51 mode. Other common values are 'w' for writing (truncating the file if 51 mode. Other common values are 'x' for creating and writing to a new
52 file, 'w' for writing (truncating the file if
52 it already exists), and 'a' for appending (which on some Unix systems, 53 it already exists), and 'a' for appending (which on some Unix systems,
53 means that all writes append to the end of the file regardless of the 54 means that all writes append to the end of the file regardless of the
54 current seek position). In text mode, if encoding is not specified the 55 current seek position). In text mode, if encoding is not specified the
55 encoding used is platform dependent. (For reading and writing raw 56 encoding used is platform dependent. (For reading and writing raw
56 bytes use binary mode and leave encoding unspecified.) The available 57 bytes use binary mode and leave encoding unspecified.) The available
57 modes are: 58 modes are:
58 59
59 ========= =============================================================== 60 ========= ===============================================================
60 Character Meaning 61 Character Meaning
61 --------- --------------------------------------------------------------- 62 --------- ---------------------------------------------------------------
62 'r' open for reading (default) 63 'r' open for reading (default)
64 'x' create a new file and open it for writing
63 'w' open for writing, truncating the file first 65 'w' open for writing, truncating the file first
64 'a' open for writing, appending to the end of the file if it exists 66 'a' open for writing, appending to the end of the file if it exists
65 'b' binary mode 67 'b' binary mode
66 't' text mode (default) 68 't' text mode (default)
67 '+' open a disk file for updating (reading and writing) 69 '+' open a disk file for updating (reading and writing)
68 'U' universal newline mode (for backwards compatibility; unneeded 70 'U' universal newline mode (for backwards compatibility; unneeded
69 for new code) 71 for new code)
70 ========= =============================================================== 72 ========= ===============================================================
71 73
72 The default mode is 'rt' (open for reading text). For binary random 74 The default mode is 'rt' (open for reading text). For binary random
73 access, the mode 'w+b' opens and truncates the file to 0 bytes, while 75 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
74 'r+b' opens the file without truncation. 76 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
77 raises an `IOError` if the file already exists.
Benjamin Peterson 2012/01/08 16:16:10 :exc:`OSError` again.
75 78
76 Python distinguishes between files opened in binary and text modes, 79 Python distinguishes between files opened in binary and text modes,
77 even when the underlying operating system doesn't. Files opened in 80 even when the underlying operating system doesn't. Files opened in
78 binary mode (appending 'b' to the mode argument) return contents as 81 binary mode (appending 'b' to the mode argument) return contents as
79 bytes objects without any decoding. In text mode (the default, or when 82 bytes objects without any decoding. In text mode (the default, or when
80 't' is appended to the mode argument), the contents of the file are 83 't' is appended to the mode argument), the contents of the file are
81 returned as strings, the bytes having been first decoded using a 84 returned as strings, the bytes having been first decoded using a
82 platform-dependent encoding or using the specified encoding if given. 85 platform-dependent encoding or using the specified encoding if given.
83 86
84 buffering is an optional integer used to set the buffering policy. 87 buffering is an optional integer used to set the buffering policy.
(...skipping 64 matching lines...) Expand 10 before | Expand all | Expand 10 after
149 raise TypeError("invalid file: %r" % file) 152 raise TypeError("invalid file: %r" % file)
150 if not isinstance(mode, str): 153 if not isinstance(mode, str):
151 raise TypeError("invalid mode: %r" % mode) 154 raise TypeError("invalid mode: %r" % mode)
152 if not isinstance(buffering, int): 155 if not isinstance(buffering, int):
153 raise TypeError("invalid buffering: %r" % buffering) 156 raise TypeError("invalid buffering: %r" % buffering)
154 if encoding is not None and not isinstance(encoding, str): 157 if encoding is not None and not isinstance(encoding, str):
155 raise TypeError("invalid encoding: %r" % encoding) 158 raise TypeError("invalid encoding: %r" % encoding)
156 if errors is not None and not isinstance(errors, str): 159 if errors is not None and not isinstance(errors, str):
157 raise TypeError("invalid errors: %r" % errors) 160 raise TypeError("invalid errors: %r" % errors)
158 modes = set(mode) 161 modes = set(mode)
159 if modes - set("arwb+tU") or len(mode) > len(modes): 162 if modes - set("axrwb+tU") or len(mode) > len(modes):
160 raise ValueError("invalid mode: %r" % mode) 163 raise ValueError("invalid mode: %r" % mode)
164 creating = "x" in modes
161 reading = "r" in modes 165 reading = "r" in modes
162 writing = "w" in modes 166 writing = "w" in modes
163 appending = "a" in modes 167 appending = "a" in modes
164 updating = "+" in modes 168 updating = "+" in modes
165 text = "t" in modes 169 text = "t" in modes
166 binary = "b" in modes 170 binary = "b" in modes
167 if "U" in modes: 171 if "U" in modes:
168 if writing or appending: 172 if creating or writing or appending:
169 raise ValueError("can't use U and writing mode at once") 173 raise ValueError("can't use U and writing mode at once")
170 reading = True 174 reading = True
171 if text and binary: 175 if text and binary:
172 raise ValueError("can't have text and binary mode at once") 176 raise ValueError("can't have text and binary mode at once")
173 if reading + writing + appending > 1: 177 if creating + reading + writing + appending > 1:
174 raise ValueError("can't have read/write/append mode at once") 178 raise ValueError("can't have read/write/append mode at once")
175 if not (reading or writing or appending): 179 if not (creating + reading or writing or appending):
176 raise ValueError("must have exactly one of read/write/append mode") 180 raise ValueError("must have exactly one of read/write/append mode")
177 if binary and encoding is not None: 181 if binary and encoding is not None:
178 raise ValueError("binary mode doesn't take an encoding argument") 182 raise ValueError("binary mode doesn't take an encoding argument")
179 if binary and errors is not None: 183 if binary and errors is not None:
180 raise ValueError("binary mode doesn't take an errors argument") 184 raise ValueError("binary mode doesn't take an errors argument")
181 if binary and newline is not None: 185 if binary and newline is not None:
182 raise ValueError("binary mode doesn't take a newline argument") 186 raise ValueError("binary mode doesn't take a newline argument")
183 raw = FileIO(file, 187 raw = FileIO(file,
188 (creating and "x" or "") +
184 (reading and "r" or "") + 189 (reading and "r" or "") +
185 (writing and "w" or "") + 190 (writing and "w" or "") +
186 (appending and "a" or "") + 191 (appending and "a" or "") +
187 (updating and "+" or ""), 192 (updating and "+" or ""),
188 closefd) 193 closefd)
189 line_buffering = False 194 line_buffering = False
190 if buffering == 1 or buffering < 0 and raw.isatty(): 195 if buffering == 1 or buffering < 0 and raw.isatty():
191 buffering = -1 196 buffering = -1
192 line_buffering = True 197 line_buffering = True
193 if buffering < 0: 198 if buffering < 0:
194 buffering = DEFAULT_BUFFER_SIZE 199 buffering = DEFAULT_BUFFER_SIZE
195 try: 200 try:
196 bs = os.fstat(raw.fileno()).st_blksize 201 bs = os.fstat(raw.fileno()).st_blksize
197 except (os.error, AttributeError): 202 except (os.error, AttributeError):
198 pass 203 pass
199 else: 204 else:
200 if bs > 1: 205 if bs > 1:
201 buffering = bs 206 buffering = bs
202 if buffering < 0: 207 if buffering < 0:
203 raise ValueError("invalid buffering size") 208 raise ValueError("invalid buffering size")
204 if buffering == 0: 209 if buffering == 0:
205 if binary: 210 if binary:
206 return raw 211 return raw
207 raise ValueError("can't have unbuffered text I/O") 212 raise ValueError("can't have unbuffered text I/O")
208 if updating: 213 if updating:
209 buffer = BufferedRandom(raw, buffering) 214 buffer = BufferedRandom(raw, buffering)
210 elif writing or appending: 215 elif creating or writing or appending:
211 buffer = BufferedWriter(raw, buffering) 216 buffer = BufferedWriter(raw, buffering)
212 elif reading: 217 elif reading:
213 buffer = BufferedReader(raw, buffering) 218 buffer = BufferedReader(raw, buffering)
214 else: 219 else:
215 raise ValueError("unknown mode: %r" % mode) 220 raise ValueError("unknown mode: %r" % mode)
216 if binary: 221 if binary:
217 return buffer 222 return buffer
218 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering) 223 text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering)
219 text.mode = mode 224 text.mode = mode
220 return text 225 return text
(...skipping 1852 matching lines...) Expand 10 before | Expand all | Expand 10 after
2073 def errors(self): 2078 def errors(self):
2074 return None 2079 return None
2075 2080
2076 @property 2081 @property
2077 def encoding(self): 2082 def encoding(self):
2078 return None 2083 return None
2079 2084
2080 def detach(self): 2085 def detach(self):
2081 # This doesn't make sense on StringIO. 2086 # This doesn't make sense on StringIO.
2082 self._unsupported("detach") 2087 self._unsupported("detach")
OLDNEW

RSS Feeds Recent Issues | This issue
This is Rietveld cbc36f91f3f7