Skip to content

Commit f4e3608

Browse files
committed
python3: use io.open() rather than open() in read_file() and create_file()
1 parent e11cfb4 commit f4e3608

File tree

2 files changed

+30
-9
lines changed

2 files changed

+30
-9
lines changed

trac/util/__init__.py

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -232,23 +232,43 @@ def __exit__(self, exc_type, exc_value, traceback):
232232
closed = property(lambda self: self._file is None or self._file.closed)
233233

234234

235-
def read_file(path, mode='r'):
235+
def read_file(path, mode='r', encoding=None, errors=None, newline=None):
236236
"""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:
238243
return f.read()
239244

240245

241-
def create_file(path, data='', mode='w'):
246+
def create_file(path, data=None, mode='w', encoding=None, errors=None,
247+
newline=None):
242248
"""Create a new file with the given data.
243249
244250
:data: string or iterable of strings.
245251
"""
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:
248264
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)
252272

253273

254274
def create_unique_file(path):

trac/wiki/admin.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ def import_page(self, filename, title, create_only=[],
118118
data = read_file(filename)
119119
else:
120120
data = sys.stdin.read()
121-
data = to_unicode(data, 'utf-8')
121+
if isinstance(data, bytes):
122+
data = data.decode('utf-8')
122123

123124
with self.env.db_transaction as db:
124125
# Make sure we don't insert the exact same page twice

0 commit comments

Comments
 (0)