当前位置: 首页>>代码示例>>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;未经允许,请勿转载。