Robot Framework
filereader.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 io import StringIO
17 import os.path
18 
19 from .robottypes import is_bytes, is_pathlike, is_string
20 
21 
22 
40 class FileReader:
41 
42  def __init__(self, source, accept_text=False):
43  self.file, self.name, self._opened_opened = self._get_file_get_file(source, accept_text)
44 
45  def _get_file(self, source, accept_text):
46  path = self._get_path_get_path(source, accept_text)
47  if path:
48  file = open(path, 'rb')
49  opened = True
50  elif is_string(source):
51  file = StringIO(source)
52  opened = True
53  else:
54  file = source
55  opened = False
56  name = getattr(file, 'name', '<in-memory file>')
57  return file, name, opened
58 
59  def _get_path(self, source, accept_text):
60  if is_pathlike(source):
61  return str(source)
62  if not is_string(source):
63  return None
64  if not accept_text:
65  return source
66  if '\n' in source:
67  return None
68  if os.path.isabs(source) or os.path.exists(source):
69  return source
70  return None
71 
72  def __enter__(self):
73  return self
74 
75  def __exit__(self, *exc_info):
76  if self._opened_opened:
77  self.file.close()
78 
79  def read(self):
80  return self._decode_decode(self.file.read())
81 
82  def readlines(self):
83  first_line = True
84  for line in self.file.readlines():
85  yield self._decode_decode(line, remove_bom=first_line)
86  first_line = False
87 
88  def _decode(self, content, remove_bom=True):
89  if is_bytes(content):
90  content = content.decode('UTF-8')
91  if remove_bom and content.startswith('\ufeff'):
92  content = content[1:]
93  if '\r\n' in content:
94  content = content.replace('\r\n', '\n')
95  return content
96 
97  def _is_binary_file(self):
98  mode = getattr(self.file, 'mode', '')
99  encoding = getattr(self.file, 'encoding', 'ascii').lower()
100  return 'r' in mode and encoding == 'ascii'
Utility to ease reading different kind of files.
Definition: filereader.py:40
def _decode(self, content, remove_bom=True)
Definition: filereader.py:88
def __init__(self, source, accept_text=False)
Definition: filereader.py:42
def _get_path(self, source, accept_text)
Definition: filereader.py:59
def __exit__(self, *exc_info)
Definition: filereader.py:75
def _get_file(self, source, accept_text)
Definition: filereader.py:45