當前位置: 首頁>>代碼示例>>Python>>正文


Python csv.Error方法代碼示例

本文整理匯總了Python中csv.Error方法的典型用法代碼示例。如果您正苦於以下問題:Python csv.Error方法的具體用法?Python csv.Error怎麽用?Python csv.Error使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在csv的用法示例。


在下文中一共展示了csv.Error方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __call__

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
def __call__(self, value):

        if value is None or isinstance(value, list):
            return value

        try:
            value = next(csv.reader([value], self.Dialect))
        except csv.Error as error:
            raise ValueError(error)

        if self._validator is None:
            return value

        try:
            for index, item in enumerate(value):
                value[index] = self._validator(item)
        except ValueError as error:
            raise ValueError('Could not convert item {}: {}'.format(index, error))

        return value 
開發者ID:remg427,項目名稱:misp42splunk,代碼行數:22,代碼來源:validators.py

示例2: clean_file

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
def clean_file(self):
        file = self.cleaned_data['file']

        if file is not None and (not file.name.endswith('.csv')) and \
                (not file.name.endswith('.CSV')):
            raise forms.ValidationError("Only .csv files are permitted")

        try:
            data = file.read().decode('utf-8-sig').splitlines()
        except UnicodeDecodeError:
            raise forms.ValidationError("Bad UTF-8 data in file.")

        try:
            # Convert the csv reader data to a list, because we need to use it twice.  If we just leave it as a csv
            # reader object, the iterator will be exhausted by the time we call this with save=True
            # First, read everything:
            reader = csv.reader(data, delimiter=',')
            # Then, convert to a list and remove any leading/trailing spaces in individual values.
            data = [[x.strip() for x in row] for row in reader]
        except csv.Error as e:
            raise forms.ValidationError('CSV decoding error.  Exception was: "' + str(e) + '"')
        # actually parse the input to see if it's valid.  If we make it through this without a ValidationError (in
        # the helper method, it's hopefully safe to call it in the view to actually create the assets.
        assets_from_csv(self.request, data, save=False)
        return data 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:27,代碼來源:forms.py

示例3: __call__

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
def __call__(self, value):

        if value is None or isinstance(value, list):
            return value

        try:
            value = csv.reader([value], self.Dialect).next()
        except csv.Error as error:
            raise ValueError(error)

        if self._validator is None:
            return value

        try:
            for index, item in enumerate(value):
                value[index] = self._validator(item)
        except ValueError as error:
            raise ValueError('Could not convert item {}: {}'.format(index, error))

        return value 
開發者ID:DanielSchwartz1,項目名稱:SplunkForPCAP,代碼行數:22,代碼來源:validators.py

示例4: _test_arg_valid

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
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) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:19,代碼來源:test_csv.py

示例5: test_write_arg_valid

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
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()]) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:19,代碼來源:test_csv.py

示例6: test_write_escape

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
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) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:18,代碼來源:test_csv.py

示例7: test_read_bigfield

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
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) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:20,代碼來源:test_csv.py

示例8: test_registry_badargs

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
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, []) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:18,代碼來源:test_csv.py

示例9: test_lineterminator

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
def test_lineterminator(self):
        class mydialect(csv.Dialect):
            delimiter = ";"
            escapechar = '\\'
            doublequote = False
            skipinitialspace = True
            lineterminator = '\r\n'
            quoting = csv.QUOTE_NONE
        d = mydialect()
        self.assertEqual(d.lineterminator, '\r\n')

        mydialect.lineterminator = ":::"
        d = mydialect()
        self.assertEqual(d.lineterminator, ":::")

        mydialect.lineterminator = 4
        with self.assertRaises(csv.Error) as cm:
            mydialect()
        self.assertEqual(str(cm.exception),
                         '"lineterminator" must be a string') 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:22,代碼來源:test_csv.py

示例10: parse_comma_separated_string

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
def parse_comma_separated_string(input_string):
    """
    Parse a string that contains a list of comma-separated values and return the list of values.
    Each value may be quoted with a doublequote, and doublequotes may be escaped with a backslash.
    Whitespace immediately following a delimiter is skipped.
    Raise a CompareError if the input is malformed.
    :param input_string: an input string
    :return: a list of strings
    """
    # We use Python's csv module because it supports quoted values
    try:
        reader = csv.reader([input_string], strict=True, skipinitialspace=True, doublequote=False, escapechar="\\")
        rows = list(reader)
    except csv.Error as exx:
        raise CompareError(u"Malformed comma-separated value: {!r}".format(input_string, exx))
    return rows[0] 
開發者ID:privacyidea,項目名稱:privacyidea,代碼行數:18,代碼來源:compare.py

示例11: test_write_arg_valid

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
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()], '') 
開發者ID:dxwu,項目名稱:BinderFilter,代碼行數:20,代碼來源:test_csv.py

示例12: test_write_escape

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
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) 
開發者ID:dxwu,項目名稱:BinderFilter,代碼行數:20,代碼來源:test_csv.py

示例13: test_quoting

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
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) 
開發者ID:dxwu,項目名稱:BinderFilter,代碼行數:25,代碼來源:test_csv.py

示例14: _get_reader

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
def _get_reader(self, data):
        """Return the CSV reader for the data using the configured delimiter, etc

        Returns:
            StringIO: Open CSV reader object or False upon error
        """
        try:
            if isinstance(data, bytes):
                data = data.decode()
            return csv.reader(
                io.StringIO(data),
                delimiter=self.delimiter,
                quotechar=self.quotechar,
                escapechar=self.escapechar
            )
        except (ValueError, csv.Error):
            return False 
開發者ID:airbnb,項目名稱:streamalert,代碼行數:19,代碼來源:parsers.py

示例15: _validate_usecols_names

# 需要導入模塊: import csv [as 別名]
# 或者: from csv import Error [as 別名]
def _validate_usecols_names(usecols, names):
    """
    Validates that all usecols are present in a given
    list of names. If not, raise a ValueError that
    shows what usecols are missing.

    Parameters
    ----------
    usecols : iterable of usecols
        The columns to validate are present in names.
    names : iterable of names
        The column names to check against.

    Returns
    -------
    usecols : iterable of usecols
        The `usecols` parameter if the validation succeeds.

    Raises
    ------
    ValueError : Columns were missing. Error message will list them.
    """
    missing = [c for c in usecols if c not in names]
    if len(missing) > 0:
        raise ValueError(
            "Usecols do not match columns, "
            "columns expected but not found: {missing}".format(missing=missing)
        )

    return usecols 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:32,代碼來源:parsers.py


注:本文中的csv.Error方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。