Python csv.register_dialect方法代码示例

本文整理汇总了Python中csv.register_dialect方法的典型用法代码示例。如果您正苦于以下问题:Python csv.register_dialect方法的具体用法?Python csv.register_dialect怎么用?Python csv.register_dialect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块csv的用法示例。

在下文中一共展示了csv.register_dialect方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_registry_badargs

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [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


示例2: test_dialect_str

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def test_dialect_str(self):
        data = """\
fruit:vegetable
apple:brocolli
pear:tomato
"""
        exp = DataFrame({
            'fruit': ['apple', 'pear'],
            'vegetable': ['brocolli', 'tomato']
        })
        csv.register_dialect('mydialect', delimiter=':')
        with tm.assert_produces_warning(ParserWarning):
            df = self.read_csv(StringIO(data), dialect='mydialect')
        tm.assert_frame_equal(df, exp)
        csv.unregister_dialect('mydialect') 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:18,代码来源:dialect.py


示例3: to_trec_eval_row

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def to_trec_eval_row(self, alternative_exp_name=None, page_only=False):
        exp_name_ = alternative_exp_name if alternative_exp_name is not  None \
                    else self.exp_name
        return [self.query_id, 'Q0', self.paragraph_id, self.rank, self.score, exp_name_]
#
# csv.register_dialect(
#     'trec_eval',
#     delimiter = ' ',
#     quotechar = '"',
#     doublequote = False,
#     skipinitialspace = False,
#     lineterminator = '\n',
#     quoting = csv.QUOTE_NONE)
#
#
# def configure_csv_writer(fileobj):
#     'Convenience method to create a csv writer with the trec_eval_dialect'
#     return csv.writer(fileobj, dialect='trec_eval')
# 
开发者ID:TREMA-UNH,项目名称:trec-car-tools,代码行数:22,代码来源:format_runs.py


示例4: cert_check

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def cert_check(self, wo_domain_name):
        """Check certificate existance with acme.sh and return Boolean"""
        WOAcme.export_cert(self)
        # set variable acme_cert
        acme_cert = False
        # define new csv dialect
        csv.register_dialect('acmeconf', delimiter='|')
        # open file
        certfile = open('/var/lib/wo/cert.csv', mode='r', encoding='utf-8')
        reader = csv.reader(certfile, 'acmeconf')
        for row in reader:
            # check if domain exist
            if wo_domain_name == row[0]:
                # check if cert expiration exist
                if not row[3] == '':
                    acme_cert = True
        certfile.close()
        if acme_cert is True:
            if os.path.exists(
                '/etc/letsencrypt/live/{0}/fullchain.pem'
                    .format(wo_domain_name)):
                return True
        return False 
开发者ID:WordOps,项目名称:WordOps,代码行数:25,代码来源:acme.py


示例5: checkwildcardexist

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def checkwildcardexist(self, wo_domain_name):
        """Check if a wildcard certificate exist for a domain"""
        wo_acme_exec = ("/etc/letsencrypt/acme.sh --config-home "
                        "'/etc/letsencrypt/config'")
        # export certificates list from acme.sh
        WOShellExec.cmd_exec(
            self, "{0} ".format(wo_acme_exec) +
            "--list --listraw > /var/lib/wo/cert.csv")
        # define new csv dialect
        csv.register_dialect('acmeconf', delimiter='|')
        # open file
        certfile = open('/var/lib/wo/cert.csv', mode='r', encoding='utf-8')
        reader = csv.reader(certfile, 'acmeconf')
        wo_wildcard_domain = ("*.{0}".format(wo_domain_name))
        for row in reader:
            if wo_wildcard_domain == row[2]:
                if not row[3] == "":
                    return True
        certfile.close()
        return False 
开发者ID:WordOps,项目名称:WordOps,代码行数:24,代码来源:sslutils.py


示例6: test_dialect_apply

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def test_dialect_apply(self):
        class testA(csv.excel):
            delimiter = "\t"
        class testB(csv.excel):
            delimiter = ":"
        class testC(csv.excel):
            delimiter = "|"
        class testUni(csv.excel):
            delimiter = "\u039B"
        csv.register_dialect('testC', testC)
        try:
            self.compare_dialect_123("1,2,3\r\n")
            self.compare_dialect_123("1\t2\t3\r\n", testA)
            self.compare_dialect_123("1:2:3\r\n", dialect=testB())
            self.compare_dialect_123("1|2|3\r\n", dialect='testC')
            self.compare_dialect_123("1;2;3\r\n", dialect=testA,
                                     delimiter=';')
            self.compare_dialect_123("1\u039B2\u039B3\r\n",
                                     dialect=testUni)
        finally:
            csv.unregister_dialect('testC') 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:25,代码来源:test_csv.py


示例7: read_from_file

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def read_from_file(self, f, messenger):
        csv.register_dialect(
            'bank_csv',
            self.account_config.get_csv_dialect()
        )
        c = csv.reader(f, 'bank_csv')
        consume(c, self.account_config.dropped_lines)  # ignore first lines
        transactions = []
        for line in c:
            try:
                transaction = self.create_from_line(line)
                transactions.append(transaction)
                messenger.send_message("parsed: " + transaction.__str__())
            except IndexError:
                messenger.send_message('skipped: %s' % line)
                continue
        return transactions 
开发者ID:niknow,项目名称:BankCSVtoQif,代码行数:19,代码来源:transaction.py


示例8: readLogData

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def readLogData(inputfile):
    """FIO log data is imported as CSV data. The scope is the import of a
    single file.
    """
    dataset = []
    if os.path.exists(inputfile):
        with open(inputfile) as csv_file:
            csv.register_dialect('CustomDialect', skipinitialspace=True,
                                 strict=True)
            csv_reader = csv.DictReader(
                csv_file, dialect='CustomDialect', delimiter=',',
                fieldnames=['timestamp', 'value', 'rwt', 'blocksize', 'offset'])
            for item in csv_reader:
                dataset.append(item)
    dataset = parse_raw_cvs_data(dataset)
    return dataset 
开发者ID:louwrentius,项目名称:fio-plot,代码行数:18,代码来源:dataimport.py


示例9: __init__

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def __init__(self, http, xmlRepGenerator):
        Attack.__init__(self, http, xmlRepGenerator)
        user_config_dir = os.getenv('HOME') or os.getenv('USERPROFILE')
        user_config_dir += "/config"
        if not os.path.isdir(user_config_dir):
            os.makedirs(user_config_dir)
        try:
            fd = open(os.path.join(user_config_dir, self.CONFIG_FILE))
            reader = csv.reader(fd)
            self.nikto_db = [l for l in reader if l != [] and l[0].isdigit()]
            fd.close()
        except IOError:
            try:
                print(_("Problem with local nikto database."))
                print(_("Downloading from the web..."))
                nikto_req = HTTP.HTTPResource("http://cirt.net/nikto/UPDATES/2.1.5/db_tests")
                resp = self.HTTP.send(nikto_req)
                page = resp.getRawPage()
                csv.register_dialect("nikto", quoting=csv.QUOTE_ALL, doublequote=False, escapechar="\\")
                reader = csv.reader(page.split("\n"), "nikto")
                self.nikto_db = [l for l in reader if l != [] and l[0].isdigit()]
                fd = open(os.path.join(user_config_dir, self.CONFIG_FILE), "w")
                writer = csv.writer(fd)
                writer.writerows(self.nikto_db)
                fd.close()
            except socket.timeout:
                print(_("Error downloading Nikto database")) 
开发者ID:flipkart-incubator,项目名称:watchdog,代码行数:31,代码来源:mod_nikto.py


示例10: with_csv_dialect

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def with_csv_dialect(name, **kwargs):
    """
    Context manager to temporarily register a CSV dialect for parsing CSV.
    Parameters
    ----------
    name : str
        The name of the dialect.
    kwargs : mapping
        The parameters for the dialect.
    Raises
    ------
    ValueError : the name of the dialect conflicts with a builtin one.
    See Also
    --------
    csv : Python's CSV library.
    """
    import csv
    _BUILTIN_DIALECTS = {"excel", "excel-tab", "unix"}
    if name in _BUILTIN_DIALECTS:
        raise ValueError("Cannot override builtin dialect.")
    csv.register_dialect(name, **kwargs)
    yield
    csv.unregister_dialect(name) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:30,代码来源:testing.py


示例11: test_registry

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def test_registry(self):
        class myexceltsv(csv.excel):
            delimiter = "\t"
        name = "myexceltsv"
        expected_dialects = csv.list_dialects() + [name]
        expected_dialects.sort()
        csv.register_dialect(name, myexceltsv)
        self.addCleanup(csv.unregister_dialect, name)
        self.assertEqual(csv.get_dialect(name).delimiter, '\t')
        got_dialects = sorted(csv.list_dialects())
        self.assertEqual(expected_dialects, got_dialects) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:13,代码来源:test_csv.py


示例12: test_register_kwargs

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def test_register_kwargs(self):
        name = 'fedcba'
        csv.register_dialect(name, delimiter=';')
        self.addCleanup(csv.unregister_dialect, name)
        self.assertEqual(csv.get_dialect(name).delimiter, ';')
        self.assertEqual([['X', 'Y', 'Z']], list(csv.reader(['X;Y;Z'], name))) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:8,代码来源:test_csv.py


示例13: from_file

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def from_file(self, input_file=None, delimiter=None):
        self._startup()
        input_file = str(input_file) if input_file is not None else None
        if not os.path.exists(input_file):
            raise Exception('TLD Input file Not Found')
        LOG.info("Importing TLDs from %s", input_file)
        error_lines = []
        tlds_added = 0
        with open(input_file) as inf:
            csv.register_dialect('import-tlds', delimiter=str(delimiter))
            reader = csv.DictReader(inf,
                                    fieldnames=['name', 'description'],
                                    restkey='extra_fields',
                                    dialect='import-tlds')
            for line in reader:
                # check if there are more than 2 fields
                if 'extra_fields' in line:
                    error_lines.append("InvalidLine --> " +
                                       self._convert_tld_dict_to_str(line))
                else:
                    tlds_added += self._validate_and_create_tld(line,
                                                                error_lines)
        LOG.info("Number of tlds added: %d", tlds_added)
        errors = len(error_lines)
        if errors > 0:
            LOG.error("Number of errors: %d", errors)
            # Sorting the errors and printing them so that it is easier to
            # read the errors
            LOG.error("Error Lines:\n%s", '\n'.join(sorted(error_lines))) 
开发者ID:openstack,项目名称:designate,代码行数:37,代码来源:tlds.py


示例14: __init__

# 需要导入模块: import csv [as 别名]
# 或者: from csv import register_dialect [as 别名]
def __init__(self, crawler, persister, logger, attack_options):
        Attack.__init__(self, crawler, persister, logger, attack_options)
        user_config_dir = os.getenv("HOME") or os.getenv("USERPROFILE")
        user_config_dir += "/config"
        if not os.path.isdir(user_config_dir):
            os.makedirs(user_config_dir)
        try:
            with open(os.path.join(user_config_dir, self.NIKTO_DB)) as fd:
                reader = csv.reader(fd)
                self.nikto_db = [line for line in reader if line != [] and line[0].isdigit()]
        except IOError:
            try:
                print(_("Problem with local nikto database."))
                print(_("Downloading from the web..."))
                nikto_req = web.Request("http://cirt.net/nikto/UPDATES/2.1.5/db_tests")
                response = self.crawler.send(nikto_req)
                csv.register_dialect("nikto", quoting=csv.QUOTE_ALL, doublequote=False, escapechar="\\")
                reader = csv.reader(response.content.split("\n"), "nikto")
                self.nikto_db = [line for line in reader if line != [] and line[0].isdigit()]
                with open(os.path.join(user_config_dir, self.NIKTO_DB), "w") as fd:
                    writer = csv.writer(fd)
                    writer.writerows(self.nikto_db)
            except socket.timeout:
                print(_("Error downloading Nikto database")) 
开发者ID:penetrate2hack,项目名称:ITWSV,代码行数:30,代码来源:mod_nikto.py



注:本文中的csv.register_dialect方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。