@@ -232,23 +232,43 @@ def __exit__(self, exc_type, exc_value, traceback):
232
232
closed = property (lambda self : self ._file is None or self ._file .closed )
233
233
234
234
235
- def read_file (path , mode = 'r' ):
235
+ def read_file (path , mode = 'r' , encoding = None , errors = None , newline = None ):
236
236
"""Read a file and return its content."""
237
- with open (path , mode ) as f :
237
+ kwargs = {}
238
+ if 'b' not in mode :
239
+ kwargs ['encoding' ] = encoding or 'utf-8'
240
+ kwargs ['errors' ] = errors
241
+ kwargs ['newline' ] = newline
242
+ with io .open (path , mode = mode , ** kwargs ) as f :
238
243
return f .read ()
239
244
240
245
241
- def create_file (path , data = '' , mode = 'w' ):
246
+ def create_file (path , data = None , mode = 'w' , encoding = None , errors = None ,
247
+ newline = None ):
242
248
"""Create a new file with the given data.
243
249
244
250
:data: string or iterable of strings.
245
251
"""
246
- with open (path , mode ) as f :
247
- if data :
252
+ binary = 'b' in mode
253
+ if encoding is None :
254
+ encoding = 'utf-8'
255
+ if errors is None :
256
+ errors = 'strict'
257
+ kwargs = {}
258
+ if 'b' not in mode :
259
+ kwargs ['encoding' ] = encoding
260
+ kwargs ['errors' ] = errors
261
+ kwargs ['newline' ] = newline
262
+ with io .open (path , mode , ** kwargs ) as f :
263
+ if data is not None :
248
264
if isinstance (data , (unicode , bytes )):
249
- f .write (data )
250
- else : # Assume iterable
251
- f .writelines (data )
265
+ data = (data ,)
266
+ for chunk in data :
267
+ if not chunk :
268
+ continue
269
+ if not binary and isinstance (chunk , bytes ):
270
+ chunk = chunk .decode (encoding , errors )
271
+ f .write (chunk )
252
272
253
273
254
274
def create_unique_file (path ):
0 commit comments