Robot Framework Integrated Development Environment (RIDE)
utf8reader.py
Go to the documentation of this file.
1 # Copyright 2008-2015 Nokia Networks
2 # Copyright 2016- Robot Framework Foundation
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 from codecs import BOM_UTF8
17 
18 from .robottypes import is_string
19 
20 
21 class Utf8Reader():
22 
23  def __init__(self, path_or_file):
24  if is_string(path_or_file):
25  self._file_file = open(path_or_file, 'rb')
26  self._close_close = True
27  else:
28  self._file_file = path_or_file
29  self._close_close = False
30  # IronPython handles BOM incorrectly if file not opened in binary mode:
31  # https://ironpython.codeplex.com/workitem/34655
32  if hasattr(self._file_file, 'mode') and self._file_file.mode != 'rb':
33  raise ValueError('Only files in binary mode accepted.')
34 
35  def __enter__(self):
36  return self
37 
38  def __exit__(self, *exc_info):
39  if self._close_close:
40  self._file_file.close()
41 
42  def read(self):
43  return self._decode_decode(self._file_file.read())
44 
45  def readlines(self):
46  for index, line in enumerate(self._file_file.readlines()):
47  yield self._decode_decode(line, remove_bom=index == 0)
48 
49  def _decode(self, content, remove_bom=True):
50  if remove_bom and content.startswith(BOM_UTF8):
51  content = content[len(BOM_UTF8):]
52  return content.decode('UTF-8')
def _decode(self, content, remove_bom=True)
Definition: utf8reader.py:49