def _show_file(filename, line_indent=' ', sort=True): lines_read = 0 with errors.converted(IOError, to=errors.DataFileError): with open(filename) as data_file: for line in (sorted(data_file) if sort else data_file): print line_indent + line.strip() lines_read += 1 return lines_read
def from_file(cls, path): with errors.converted((IOError, TypeError), to=errors.DataFileError): fields = {field: [] for field in RunRecord._fields} run_time = None with open(path) as record: for line in record: line_type = RunRecord._line_types.get(line[0]) if line_type in fields: fields[line_type].append(util.strip_line_labels(line)) elif line.startswith('='): run_time = re.search(r'\[(.*)\]', line).group(1) timestamp = datetime.strptime(run_time, RunRecord.time_format) return RunRecord(when=timestamp, **fields)
def load_from_file(name_or_handle, test_class=Test, line_filter=None): """Reads a file containing paths to test files (dirnames + basenames) and returns them as a list of [test_class] objects. Any non-blank, non-whitespace line is treated as a valid path. [name_or_handle] is a filename or an open file-like object. If an open file is given, it will be fully read but won't be closed. [line_filter] is an optional function that takes a line and returns either False or a string. If truthy, its output will be used in place of the original line. """ line_filter = (lambda x: x) if line_filter is None else line_filter def get_tests(handle): tests = [] for line in handle: if line.strip() == '': continue line = line_filter(line) if line: tests.append(test_class(line)) return tests with errors.converted((IOError, OSError), to=errors.DataFileError): try: with open(name_or_handle) as file_handle: return get_tests(file_handle) except TypeError: # Got passed an open file. Read it, but don't close it. return get_tests(name_or_handle) return sorted(tests)
def _generate_answer_file(self, path, contents): with errors.converted((IOError, OSError), to=errors.DataFileError): with open(path, 'w+') as answer_file: answer_file.writelines(contents.splitlines(True))