我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用csv.Error()。
def test_read_bigfield(self): # This exercises the buffer realloc functionality and field size # limits. limit = csv.field_size_limit() try: size = 50000 bigstring = 'X' * size bigline = '%s,%s' % (bigstring, bigstring) self._read_test([bigline], [[bigstring, bigstring]]) csv.field_size_limit(size) self._read_test([bigline], [[bigstring, bigstring]]) self.assertEqual(csv.field_size_limit(), size) csv.field_size_limit(size-1) self.assertRaises(csv.Error, self._read_test, [bigline], []) self.assertRaises(TypeError, csv.field_size_limit, None) self.assertRaises(TypeError, csv.field_size_limit, 1, None) finally: csv.field_size_limit(limit)
def __init__(self, f, fieldnames=None, encoding=UTF8, **kwds): self.encoding = encoding try: self.reader = csv.reader(UTF8Recoder(f, encoding) if self.encoding != UTF8 else f, dialect=csv.excel, **kwds) if not fieldnames: self.fieldnames = self.reader.next() if len(self.fieldnames) > 0 and self.fieldnames[0].startswith(codecs.BOM_UTF8): self.fieldnames[0] = self.fieldnames[0].replace(codecs.BOM_UTF8, u'', 1) else: self.fieldnames = fieldnames except (csv.Error, StopIteration): self.fieldnames = [] except LookupError as e: Cmd.Backup() usageErrorExit(e) self.numfields = len(self.fieldnames)
def _test_arg_valid(self, ctor, arg): self.assertRaises(TypeError, ctor) # PyPy gets an AttributeError instead of a TypeError self.assertRaises((TypeError, AttributeError), ctor, None) self.assertRaises(TypeError, ctor, arg, bad_attr = 0) self.assertRaises(TypeError, ctor, arg, delimiter = 0) self.assertRaises(TypeError, ctor, arg, delimiter = 'XX') self.assertRaises(csv.Error, ctor, arg, 'foo') self.assertRaises(TypeError, ctor, arg, delimiter=None) self.assertRaises(TypeError, ctor, arg, delimiter=1) self.assertRaises(TypeError, ctor, arg, quotechar=1) self.assertRaises(TypeError, ctor, arg, lineterminator=None) self.assertRaises(TypeError, ctor, arg, lineterminator=1) self.assertRaises(TypeError, ctor, arg, quoting=None) self.assertRaises(TypeError, ctor, arg, quoting=csv.QUOTE_ALL, quotechar='') self.assertRaises(TypeError, ctor, arg, quoting=csv.QUOTE_ALL, quotechar=None)
def test_write_arg_valid(self): # PyPy gets a TypeError instead of a csv.Error for "not a sequence" self.assertRaises((csv.Error, TypeError), self._write_test, None, '') self._write_test((), '') self._write_test([None], '""') self.assertRaises(csv.Error, self._write_test, [None], None, quoting = csv.QUOTE_NONE) # Check that exceptions are passed up the chain class BadList: def __len__(self): return 10; def __getitem__(self, i): if i > 2: raise IOError self.assertRaises(IOError, self._write_test, BadList(), '') class BadItem: def __str__(self): raise IOError self.assertRaises(IOError, self._write_test, [BadItem()], '')
def test_write_escape(self): self._write_test(['a',1,'p,q'], 'a,1,"p,q"', escapechar='\\') self.assertRaises(csv.Error, self._write_test, ['a',1,'p,"q"'], 'a,1,"p,\\"q\\""', escapechar=None, doublequote=False) self._write_test(['a',1,'p,"q"'], 'a,1,"p,\\"q\\""', escapechar='\\', doublequote = False) self._write_test(['"'], '""""', escapechar='\\', quoting = csv.QUOTE_MINIMAL) self._write_test(['"'], '\\"', escapechar='\\', quoting = csv.QUOTE_MINIMAL, doublequote = False) self._write_test(['"'], '\\"', escapechar='\\', quoting = csv.QUOTE_NONE) self._write_test(['a',1,'p,q'], 'a,1,p\\,q', escapechar='\\', quoting = csv.QUOTE_NONE)
def test_registry_badargs(self): self.assertRaises(TypeError, csv.list_dialects, None) self.assertRaises(TypeError, csv.get_dialect) self.assertRaises(csv.Error, csv.get_dialect, None) self.assertRaises(csv.Error, csv.get_dialect, "nonesuch") self.assertRaises(TypeError, csv.unregister_dialect) self.assertRaises(csv.Error, csv.unregister_dialect, None) self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch") self.assertRaises(TypeError, csv.register_dialect, None) self.assertRaises(TypeError, csv.register_dialect, None, None) self.assertRaises(TypeError, csv.register_dialect, "nonesuch", 0, 0) self.assertRaises(TypeError, csv.register_dialect, "nonesuch", badargument=None) self.assertRaises(TypeError, csv.register_dialect, "nonesuch", quoting=None) self.assertRaises(TypeError, csv.register_dialect, [])
def test_quoting(self): class mydialect(csv.Dialect): delimiter = ";" escapechar = '\\' doublequote = False skipinitialspace = True lineterminator = '\r\n' quoting = csv.QUOTE_NONE d = mydialect() mydialect.quoting = None self.assertRaises(csv.Error, mydialect) mydialect.doublequote = True mydialect.quoting = csv.QUOTE_ALL mydialect.quotechar = '"' d = mydialect() mydialect.quotechar = "''" self.assertRaises(csv.Error, mydialect) mydialect.quotechar = 4 self.assertRaises(csv.Error, mydialect)
def parse_row(self, row, lineno): """Parse a row of a TD Canada Trust CSV file. Args: row: A list of field values for the row. lineno: The line number where the row appears in the CSV file Returns: A beansoup.importers.csv.Row object. """ if len(row) != 5: raise csvlib.Error('Invalid row; expecting 5 values: {}'.format(row)) date = datetime.datetime.strptime(row[0], '%m/%d/%Y').date() description = row[1] amount = -D(row[2]) if row[2] else D(row[3]) balance = self.account_sign * D(row[4]) return csv.Row(lineno, date, description, amount, balance)
def __init__(self, path): super().__init__() uic.loadUi('ui/csv_import_window.ui', self) self.file_path = path self.notes = [] self.on_change = lambda: False # It is possible to validate multiple times without that self.validated = False self.amount.setValidator(api.validator.NUMBER) self.reason.setValidator(api.validator.NAME) self.recap.header().setStretchLastSection(False) self.recap.header().setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch) try: self._build_recap() except KeyError: gui.utils.error("Erreur", "Le fichier CSV fourni est mal formé") raise csv.Error else: self.show()
def csv_import_fnc(self, _): """ Open a CsvImportWindow """ if self.try_locking("notes_management"): self._close_window() path, _ = QtWidgets.QFileDialog().getOpenFileName( self, "Imported", "", "CSV Files (*.csv)" ) if path: try: self.cur_window = CsvImportWindow(path) self._connect_window("notes_management") except csv.Error: api.redis.unlock("notes_management") else: api.redis.unlock("notes_management")
def _test_arg_valid(self, ctor, arg): self.assertRaises(TypeError, ctor) self.assertRaises(TypeError, ctor, None) self.assertRaises(TypeError, ctor, arg, bad_attr = 0) self.assertRaises(TypeError, ctor, arg, delimiter = 0) self.assertRaises(TypeError, ctor, arg, delimiter = 'XX') self.assertRaises(csv.Error, ctor, arg, 'foo') self.assertRaises(TypeError, ctor, arg, delimiter=None) self.assertRaises(TypeError, ctor, arg, delimiter=1) self.assertRaises(TypeError, ctor, arg, quotechar=1) self.assertRaises(TypeError, ctor, arg, lineterminator=None) self.assertRaises(TypeError, ctor, arg, lineterminator=1) self.assertRaises(TypeError, ctor, arg, quoting=None) self.assertRaises(TypeError, ctor, arg, quoting=csv.QUOTE_ALL, quotechar='') self.assertRaises(TypeError, ctor, arg, quoting=csv.QUOTE_ALL, quotechar=None)
def test_write_arg_valid(self): self._write_error_test(csv.Error, None) self._write_test((), '') self._write_test([None], '""') self._write_error_test(csv.Error, [None], quoting = csv.QUOTE_NONE) # Check that exceptions are passed up the chain class BadList: def __len__(self): return 10; def __getitem__(self, i): if i > 2: raise IOError self._write_error_test(IOError, BadList()) class BadItem: def __str__(self): raise IOError self._write_error_test(IOError, [BadItem()])
def test_write_escape(self): self._write_test(['a',1,'p,q'], 'a,1,"p,q"', escapechar='\\') self._write_error_test(csv.Error, ['a',1,'p,"q"'], escapechar=None, doublequote=False) self._write_test(['a',1,'p,"q"'], 'a,1,"p,\\"q\\""', escapechar='\\', doublequote = False) self._write_test(['"'], '""""', escapechar='\\', quoting = csv.QUOTE_MINIMAL) self._write_test(['"'], '\\"', escapechar='\\', quoting = csv.QUOTE_MINIMAL, doublequote = False) self._write_test(['"'], '\\"', escapechar='\\', quoting = csv.QUOTE_NONE) self._write_test(['a',1,'p,q'], 'a,1,p\\,q', escapechar='\\', quoting = csv.QUOTE_NONE)
def run(self): if not self.content: warning = self.state_machine.reporter.warning( 'Content block expected for the "%s" directive; none found.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [warning] title, messages = self.make_title() node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) if len(node) != 1 or not isinstance(node[0], nodes.table): error = self.state_machine.reporter.error( 'Error parsing content block for the "%s" directive: exactly ' 'one table expected.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [error] table_node = node[0] table_node['classes'] += self.options.get('class', []) self.add_name(table_node) if title: table_node.insert(0, title) return [table_node] + messages
def test_write_arg_valid(self): self.assertRaises(csv.Error, self._write_test, None, '') self._write_test((), '') self._write_test([None], '""') self.assertRaises(csv.Error, self._write_test, [None], None, quoting = csv.QUOTE_NONE) # Check that exceptions are passed up the chain class BadList: def __len__(self): return 10; def __getitem__(self, i): if i > 2: raise IOError self.assertRaises(IOError, self._write_test, BadList(), '') class BadItem: def __str__(self): raise IOError self.assertRaises(IOError, self._write_test, [BadItem()], '')
def test_write_arg_valid(self): self._write_error_test(csv.Error, None) self._write_test((), '') self._write_test([None], '""') self._write_error_test(csv.Error, [None], quoting = csv.QUOTE_NONE) # Check that exceptions are passed up the chain class BadList: def __len__(self): return 10; def __getitem__(self, i): if i > 2: raise OSError self._write_error_test(OSError, BadList()) class BadItem: def __str__(self): raise OSError self._write_error_test(OSError, [BadItem()])
def _get_reader(self, data): """Return the CSV reader for the given payload source Returns: StringIO: CSV reader object if the parse was successful OR False if parse was unsuccessful """ delimiter = self.options.get('delimiter', self.__default_delimiter) # TODO(ryandeivert): either subclass a current parser or add a new # parser to support parsing CSV data that contains a header line try: csv_data = StringIO.StringIO(data) reader = csv.reader(csv_data, delimiter=delimiter) except (ValueError, csv.Error): return False return reader
def Readfile(file_path, remove_linebreaks=0, ignore_error=0): data = [] if file_path == '-': try: data = sys.stdin.readlines() except: if not ignore_error: Error(_('You must feed me with data on STDIN!')) else: try: f = open(file_path) data = f.readlines() f.close() except: if not ignore_error: Error(_("Cannot read file:") + ' ' + file_path) if remove_linebreaks: data = map(lambda x:re.sub('[\n\r]+$', '', x), data) Message(_("File read (%d lines): %s") % (len(data), file_path), 2) return data
def _set_prop(self, line=''): "Extract info from original line and set data holders." # Detect title type (numbered or not) id_ = line.lstrip()[0] if id_ == '=': kind = 'title' elif id_ == '+': kind = 'numtitle' else: Error("Unknown Title ID '%s'"%id_) # Extract line info match = regex[kind].search(line) level = len(match.group('id')) txt = match.group('txt').strip() label = match.group('label') # Parse info & save if CONF['enum-title']: kind = 'numtitle' # force if rules['titleblocks']: self.tag = TAGS.get('%s%dOpen'%(kind,level)) or \ TAGS.get('title%dOpen'%level) else: self.tag = TAGS.get(kind+`level`) or \ TAGS.get('title'+`level`) self.last_level = self.level self.kind = kind self.level = level self.txt = txt self.label = label
def blockin(self, block): ret = [] if block not in self.allblocks: Error("Invalid block '%s'"%block) # First, let's close other possible open blocks while self.block() and block not in self.contains[self.block()]: ret.extend(self.blockout()) # Now we can gladly add this new one self.BLK.append(block) self.HLD.append([]) self.PRP.append({}) self.count += 1 if block == 'table': self.tableparser = TableMaster() # Deeper and deeper self.depth = len(self.BLK) Debug('block ++ (%s): %s' % (block,self.BLK), 3) return ret
def expand(self, line=''): "Expand all macros found on the line" while self.rgx.search(line): m = self.rgx.search(line) name = self.name = m.group('name').lower() fmt = m.group('fmt') or self.dft_fmt.get(name) if name == 'date': txt = time.strftime(fmt,self.currdate) elif name == 'mtime': if self.infile in (STDIN, MODULEIN): fdate = self.currdate else: mtime = os.path.getmtime(self.infile) fdate = time.localtime(mtime) txt = time.strftime(fmt,fdate) elif name == 'infile' or name == 'outfile': self.set_file_info(name) txt = self.walk_file_format(fmt) else: Error("Unknown macro name '%s'"%name) line = self.rgx.sub(txt,line,1) return line ##############################################################################