gooderp18绿色标准版
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

751 lines
24KB

  1. """
  2. PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
  3. --------------------------------------------
  4. 1. This LICENSE AGREEMENT is between the Python Software Foundation
  5. ("PSF"), and the Individual or Organization ("Licensee") accessing and
  6. otherwise using this software ("Python") in source or binary form and
  7. its associated documentation.
  8. 2. Subject to the terms and conditions of this License Agreement, PSF hereby
  9. grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
  10. analyze, test, perform and/or display publicly, prepare derivative works,
  11. distribute, and otherwise use Python alone or in any derivative version,
  12. provided, however, that PSF's License Agreement and PSF's notice of copyright,
  13. i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,2010
  14. 2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Software Foundation; All Rights
  15. Reserved" are retained in Python alone or in any derivative version prepared by
  16. Licensee.
  17. 3. In the event Licensee prepares a derivative work that is based on
  18. or incorporates Python or any part thereof, and wants to make
  19. the derivative work available to others as provided herein, then
  20. Licensee hereby agrees to include in any such work a brief summary of
  21. the changes made to Python.
  22. 4. PSF is making Python available to Licensee on an "AS IS"
  23. basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
  24. IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
  25. DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
  26. FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
  27. INFRINGE ANY THIRD PARTY RIGHTS.
  28. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
  29. FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
  30. A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
  31. OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
  32. 6. This License Agreement will automatically terminate upon a material
  33. breach of its terms and conditions.
  34. 7. Nothing in this License Agreement shall be deemed to create any
  35. relationship of agency, partnership, or joint venture between PSF and
  36. Licensee. This License Agreement does not grant permission to use PSF
  37. trademarks or trade name in a trademark sense to endorse or promote
  38. products or services of Licensee, or any third party.
  39. 8. By copying, installing or otherwise using Python, Licensee
  40. agrees to be bound by the terms and conditions of this License
  41. Agreement.
  42. """
  43. ############################################################################
  44. # Changes:
  45. # Added new parameter in dialect 'replace_nulls_with' to compare it against
  46. # the value to be quoted or not.
  47. # Handle the null value if value is None or equal to
  48. # 'replace_nulls_with' then it represents the null value, so no need to
  49. # quote it.
  50. ############################################################################
  51. from __future__ import unicode_literals, absolute_import
  52. __all__ = ["QUOTE_MINIMAL", "QUOTE_ALL", "QUOTE_NONNUMERIC", "QUOTE_NONE",
  53. "Error", "Dialect", "__doc__", "Excel", "ExcelTab",
  54. "field_size_limit", "Reader", "Writer", "register_dialect",
  55. "get_dialect", "list_dialects", "unregister_dialect",
  56. "__version__", "DictReader", "DictWriter"]
  57. import re
  58. import numbers
  59. from io import StringIO
  60. from csv import (
  61. QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE,
  62. __version__, __doc__, Error, field_size_limit,
  63. )
  64. # Stuff needed from six
  65. string_types = str
  66. text_type = str
  67. binary_type = bytes
  68. unichr = chr
  69. class QuoteStrategy(object):
  70. quoting = None
  71. def __init__(self, dialect):
  72. if self.quoting is not None:
  73. assert dialect.quoting == self.quoting
  74. self.dialect = dialect
  75. self.setup()
  76. escape_pattern_quoted = r'({quotechar})'.format(
  77. quotechar=re.escape(self.dialect.quotechar or '"'))
  78. escape_pattern_unquoted = r'([{specialchars}])'.format(
  79. specialchars=re.escape(self.specialchars))
  80. self.escape_re_quoted = re.compile(escape_pattern_quoted)
  81. self.escape_re_unquoted = re.compile(escape_pattern_unquoted)
  82. def setup(self):
  83. """Optional method for strategy-wide optimizations."""
  84. def quoted(self, field=None, raw_field=None, only=None):
  85. """Determine whether this field should be quoted."""
  86. raise NotImplementedError(
  87. 'quoted must be implemented by a subclass')
  88. @property
  89. def specialchars(self):
  90. """The special characters that need to be escaped."""
  91. raise NotImplementedError(
  92. 'specialchars must be implemented by a subclass')
  93. def escape_re(self, quoted=None):
  94. if quoted:
  95. return self.escape_re_quoted
  96. return self.escape_re_unquoted
  97. def escapechar(self, quoted=None):
  98. if quoted and self.dialect.doublequote:
  99. return self.dialect.quotechar
  100. return self.dialect.escapechar
  101. def prepare(self, raw_field, only=None):
  102. field = text_type(raw_field if raw_field is not None else '')
  103. quoted = self.quoted(field=field, raw_field=raw_field, only=only)
  104. escape_re = self.escape_re(quoted=quoted)
  105. escapechar = self.escapechar(quoted=quoted)
  106. if escape_re.search(field):
  107. escapechar = '\\\\' if escapechar == '\\' else escapechar
  108. if escapechar:
  109. escape_replace = \
  110. r'{escapechar}\1'.format(escapechar=escapechar)
  111. field = escape_re.sub(escape_replace, field)
  112. if quoted:
  113. field = '{quotechar}{field}{quotechar}'.format(
  114. quotechar=self.dialect.quotechar, field=field)
  115. return field
  116. class QuoteMinimalStrategy(QuoteStrategy):
  117. quoting = QUOTE_MINIMAL
  118. def setup(self):
  119. self.quoted_re = re.compile(r'[{specialchars}]'.format(
  120. specialchars=re.escape(self.specialchars)))
  121. @property
  122. def specialchars(self):
  123. return (
  124. self.dialect.lineterminator +
  125. self.dialect.quotechar +
  126. self.dialect.delimiter +
  127. (self.dialect.escapechar or '')
  128. )
  129. def quoted(self, field, only, **kwargs):
  130. if field == self.dialect.quotechar and not self.dialect.doublequote:
  131. # If the only character in the field is the quotechar, and
  132. # doublequote is false, then just escape without outer quotes.
  133. return False
  134. return field == '' and only or bool(self.quoted_re.search(field))
  135. class QuoteAllStrategy(QuoteStrategy):
  136. quoting = QUOTE_ALL
  137. @property
  138. def specialchars(self):
  139. return self.dialect.quotechar
  140. def quoted(self, raw_field, **kwargs):
  141. # Handle the null value if raw_field is None or equal to
  142. # replace_nulls_with then it represents the null value, so no need to
  143. # quote it.
  144. if raw_field is None or raw_field == self.dialect.replace_nulls_with:
  145. return False
  146. return True
  147. class QuoteNonnumericStrategy(QuoteStrategy):
  148. quoting = QUOTE_NONNUMERIC
  149. @property
  150. def specialchars(self):
  151. return (
  152. self.dialect.lineterminator +
  153. self.dialect.quotechar +
  154. self.dialect.delimiter +
  155. (self.dialect.escapechar or '')
  156. )
  157. def quoted(self, raw_field, **kwargs):
  158. # Handle the null value if raw_field is None or equal to
  159. # replace_nulls_with then it represents the null value, so no need to
  160. # quote it.
  161. if raw_field is None or raw_field == self.dialect.replace_nulls_with:
  162. return False
  163. return not isinstance(raw_field, numbers.Number)
  164. class QuoteNoneStrategy(QuoteStrategy):
  165. quoting = QUOTE_NONE
  166. @property
  167. def specialchars(self):
  168. return (
  169. self.dialect.lineterminator +
  170. (self.dialect.quotechar or '') +
  171. self.dialect.delimiter +
  172. (self.dialect.escapechar or '')
  173. )
  174. def quoted(self, field, only, **kwargs):
  175. if field == '' and only:
  176. raise Error('single empty field record must be quoted')
  177. return False
  178. class Writer(object):
  179. def __init__(self, fileobj, dialect='excel', **fmtparams):
  180. if fileobj is None:
  181. raise TypeError('fileobj must be file-like, not None')
  182. self.fileobj = fileobj
  183. if isinstance(dialect, text_type):
  184. dialect = get_dialect(dialect)
  185. try:
  186. self.dialect = Dialect.combine(dialect, fmtparams)
  187. except Error as e:
  188. raise TypeError(*e.args)
  189. strategies = {
  190. QUOTE_MINIMAL: QuoteMinimalStrategy,
  191. QUOTE_ALL: QuoteAllStrategy,
  192. QUOTE_NONNUMERIC: QuoteNonnumericStrategy,
  193. QUOTE_NONE: QuoteNoneStrategy,
  194. }
  195. self.strategy = strategies[self.dialect.quoting](self.dialect)
  196. def writerow(self, row):
  197. if row is None:
  198. raise Error('row must be an iterable')
  199. row = list(row)
  200. only = len(row) == 1
  201. row = [self.strategy.prepare(field, only=only) for field in row]
  202. line = self.dialect.delimiter.join(row) + self.dialect.lineterminator
  203. return self.fileobj.write(line)
  204. def writerows(self, rows):
  205. for row in rows:
  206. self.writerow(row)
  207. START_RECORD = 0
  208. START_FIELD = 1
  209. ESCAPED_CHAR = 2
  210. IN_FIELD = 3
  211. IN_QUOTED_FIELD = 4
  212. ESCAPE_IN_QUOTED_FIELD = 5
  213. QUOTE_IN_QUOTED_FIELD = 6
  214. EAT_CRNL = 7
  215. AFTER_ESCAPED_CRNL = 8
  216. class Reader(object):
  217. def __init__(self, fileobj, dialect='excel', **fmtparams):
  218. self.input_iter = iter(fileobj)
  219. if isinstance(dialect, text_type):
  220. dialect = get_dialect(dialect)
  221. try:
  222. self.dialect = Dialect.combine(dialect, fmtparams)
  223. except Error as e:
  224. raise TypeError(*e.args)
  225. self.fields = None
  226. self.field = None
  227. self.line_num = 0
  228. def parse_reset(self):
  229. self.fields = []
  230. self.field = []
  231. self.state = START_RECORD
  232. self.numeric_field = False
  233. def parse_save_field(self):
  234. field = ''.join(self.field)
  235. self.field = []
  236. if self.numeric_field:
  237. field = float(field)
  238. self.numeric_field = False
  239. self.fields.append(field)
  240. def parse_add_char(self, c):
  241. if len(self.field) >= field_size_limit():
  242. raise Error('field size limit exceeded')
  243. self.field.append(c)
  244. def parse_process_char(self, c):
  245. switch = {
  246. START_RECORD: self._parse_start_record,
  247. START_FIELD: self._parse_start_field,
  248. ESCAPED_CHAR: self._parse_escaped_char,
  249. AFTER_ESCAPED_CRNL: self._parse_after_escaped_crnl,
  250. IN_FIELD: self._parse_in_field,
  251. IN_QUOTED_FIELD: self._parse_in_quoted_field,
  252. ESCAPE_IN_QUOTED_FIELD: self._parse_escape_in_quoted_field,
  253. QUOTE_IN_QUOTED_FIELD: self._parse_quote_in_quoted_field,
  254. EAT_CRNL: self._parse_eat_crnl,
  255. }
  256. return switch[self.state](c)
  257. def _parse_start_record(self, c):
  258. if c == '\0':
  259. return
  260. elif c == '\n' or c == '\r':
  261. self.state = EAT_CRNL
  262. return
  263. self.state = START_FIELD
  264. return self._parse_start_field(c)
  265. def _parse_start_field(self, c):
  266. if c == '\n' or c == '\r' or c == '\0':
  267. self.parse_save_field()
  268. self.state = START_RECORD if c == '\0' else EAT_CRNL
  269. elif (c == self.dialect.quotechar and
  270. self.dialect.quoting != QUOTE_NONE):
  271. self.state = IN_QUOTED_FIELD
  272. elif c == self.dialect.escapechar:
  273. self.state = ESCAPED_CHAR
  274. elif c == ' ' and self.dialect.skipinitialspace:
  275. pass # Ignore space at start of field
  276. elif c == self.dialect.delimiter:
  277. # Save empty field
  278. self.parse_save_field()
  279. else:
  280. # Begin new unquoted field
  281. if self.dialect.quoting == QUOTE_NONNUMERIC:
  282. self.numeric_field = True
  283. self.parse_add_char(c)
  284. self.state = IN_FIELD
  285. def _parse_escaped_char(self, c):
  286. if c == '\n' or c == '\r':
  287. self.parse_add_char(c)
  288. self.state = AFTER_ESCAPED_CRNL
  289. return
  290. if c == '\0':
  291. c = '\n'
  292. self.parse_add_char(c)
  293. self.state = IN_FIELD
  294. def _parse_after_escaped_crnl(self, c):
  295. if c == '\0':
  296. return
  297. return self._parse_in_field(c)
  298. def _parse_in_field(self, c):
  299. # In unquoted field
  300. if c == '\n' or c == '\r' or c == '\0':
  301. # End of line - return [fields]
  302. self.parse_save_field()
  303. self.state = START_RECORD if c == '\0' else EAT_CRNL
  304. elif c == self.dialect.escapechar:
  305. self.state = ESCAPED_CHAR
  306. elif c == self.dialect.delimiter:
  307. self.parse_save_field()
  308. self.state = START_FIELD
  309. else:
  310. # Normal character - save in field
  311. self.parse_add_char(c)
  312. def _parse_in_quoted_field(self, c):
  313. if c != '\0' and c == self.dialect.escapechar:
  314. self.state = ESCAPE_IN_QUOTED_FIELD
  315. elif c != '\0' and (c == self.dialect.quotechar and
  316. self.dialect.quoting != QUOTE_NONE):
  317. if self.dialect.doublequote:
  318. self.state = QUOTE_IN_QUOTED_FIELD
  319. else:
  320. self.state = IN_FIELD
  321. elif c != '\0':
  322. self.parse_add_char(c)
  323. def _parse_escape_in_quoted_field(self, c):
  324. if c == '\0':
  325. c = '\n'
  326. self.parse_add_char(c)
  327. self.state = IN_QUOTED_FIELD
  328. def _parse_quote_in_quoted_field(self, c):
  329. if (self.dialect.quoting != QUOTE_NONE and
  330. c == self.dialect.quotechar):
  331. # save "" as "
  332. self.parse_add_char(c)
  333. self.state = IN_QUOTED_FIELD
  334. elif c == self.dialect.delimiter:
  335. self.parse_save_field()
  336. self.state = START_FIELD
  337. elif c == '\n' or c == '\r' or c == '\0':
  338. # End of line = return [fields]
  339. self.parse_save_field()
  340. self.state = START_RECORD if c == '\0' else EAT_CRNL
  341. elif not self.dialect.strict:
  342. self.parse_add_char(c)
  343. self.state = IN_FIELD
  344. else:
  345. # illegal
  346. raise Error("{delimiter}' expected after '{quotechar}".format(
  347. delimiter=self.dialect.delimiter,
  348. quotechar=self.dialect.quotechar,
  349. ))
  350. def _parse_eat_crnl(self, c):
  351. if c != '\n' and c != '\r' and c == '\0':
  352. self.state = START_RECORD
  353. elif c != '\n' and c != '\r':
  354. raise Error('new-line character seen in unquoted field - do you '
  355. 'need to open the file in universal-newline mode?')
  356. def __iter__(self):
  357. return self
  358. def __next__(self):
  359. self.parse_reset()
  360. while True:
  361. try:
  362. lineobj = next(self.input_iter)
  363. except StopIteration:
  364. if len(self.field) != 0 or self.state == IN_QUOTED_FIELD:
  365. if self.dialect.strict:
  366. raise Error('unexpected end of data')
  367. self.parse_save_field()
  368. if self.fields:
  369. break
  370. raise
  371. if not isinstance(lineobj, text_type):
  372. typ = type(lineobj)
  373. typ_name = 'bytes' if typ == bytes else typ.__name__
  374. err_str = ('iterator should return strings, not {0}'
  375. ' (did you open the file in text mode?)')
  376. raise Error(err_str.format(typ_name))
  377. self.line_num += 1
  378. for c in lineobj:
  379. if c == '\0':
  380. raise Error('line contains NULL byte')
  381. self.parse_process_char(c)
  382. self.parse_process_char('\0')
  383. if self.state == START_RECORD:
  384. break
  385. fields = self.fields
  386. self.fields = None
  387. return fields
  388. next = __next__
  389. _dialect_registry = {}
  390. def register_dialect(name, dialect='excel', **fmtparams):
  391. if not isinstance(name, text_type):
  392. raise TypeError('"name" must be a string')
  393. dialect = Dialect.extend(dialect, fmtparams)
  394. try:
  395. Dialect.validate(dialect)
  396. except Exception as e:
  397. raise TypeError('dialect is invalid')
  398. assert name not in _dialect_registry
  399. _dialect_registry[name] = dialect
  400. def unregister_dialect(name):
  401. try:
  402. _dialect_registry.pop(name)
  403. except KeyError:
  404. raise Error('"{name}" not a registered dialect'.format(name=name))
  405. def get_dialect(name):
  406. try:
  407. return _dialect_registry[name]
  408. except KeyError:
  409. raise Error('Could not find dialect {0}'.format(name))
  410. def list_dialects():
  411. return list(_dialect_registry)
  412. class Dialect(object):
  413. """Describe a CSV dialect.
  414. This must be subclassed (see csv.excel). Valid attributes are:
  415. delimiter, quotechar, escapechar, doublequote, skipinitialspace,
  416. lineterminator, quoting, strict.
  417. """
  418. _name = ""
  419. _valid = False
  420. # placeholders
  421. delimiter = None
  422. quotechar = None
  423. escapechar = None
  424. doublequote = None
  425. skipinitialspace = None
  426. lineterminator = None
  427. quoting = None
  428. strict = None
  429. def __init__(self):
  430. self.validate(self)
  431. if self.__class__ != Dialect:
  432. self._valid = True
  433. @classmethod
  434. def validate(cls, dialect):
  435. dialect = cls.extend(dialect)
  436. if not isinstance(dialect.quoting, int):
  437. raise Error('"quoting" must be an integer')
  438. if dialect.delimiter is None:
  439. raise Error('delimiter must be set')
  440. cls.validate_text(dialect, 'delimiter')
  441. if dialect.lineterminator is None:
  442. raise Error('lineterminator must be set')
  443. if not isinstance(dialect.lineterminator, text_type):
  444. raise Error('"lineterminator" must be a string')
  445. if dialect.quoting not in [
  446. QUOTE_NONE, QUOTE_MINIMAL, QUOTE_NONNUMERIC, QUOTE_ALL]:
  447. raise Error('Invalid quoting specified')
  448. if dialect.quoting != QUOTE_NONE:
  449. if dialect.quotechar is None and dialect.escapechar is None:
  450. raise Error('quotechar must be set if quoting enabled')
  451. if dialect.quotechar is not None:
  452. cls.validate_text(dialect, 'quotechar')
  453. @staticmethod
  454. def validate_text(dialect, attr):
  455. val = getattr(dialect, attr)
  456. if not isinstance(val, text_type):
  457. if type(val) == bytes:
  458. raise Error('"{0}" must be string, not bytes'.format(attr))
  459. raise Error('"{0}" must be string, not {1}'.format(
  460. attr, type(val).__name__))
  461. if len(val) != 1:
  462. raise Error('"{0}" must be a 1-character string'.format(attr))
  463. @staticmethod
  464. def defaults():
  465. return {
  466. 'delimiter': ',',
  467. 'doublequote': True,
  468. 'escapechar': None,
  469. 'lineterminator': '\r\n',
  470. 'quotechar': '"',
  471. 'quoting': QUOTE_MINIMAL,
  472. 'skipinitialspace': False,
  473. 'strict': False,
  474. 'replace_nulls_with': None
  475. }
  476. @classmethod
  477. def extend(cls, dialect, fmtparams=None):
  478. if isinstance(dialect, string_types):
  479. dialect = get_dialect(dialect)
  480. if fmtparams is None:
  481. return dialect
  482. defaults = cls.defaults()
  483. if any(param not in defaults for param in fmtparams):
  484. raise TypeError('Invalid fmtparam')
  485. specified = dict(
  486. (attr, getattr(dialect, attr, None))
  487. for attr in cls.defaults()
  488. )
  489. specified.update(fmtparams)
  490. return type(str('ExtendedDialect'), (cls,), specified)
  491. @classmethod
  492. def combine(cls, dialect, fmtparams):
  493. """Create a new dialect with defaults and added parameters."""
  494. dialect = cls.extend(dialect, fmtparams)
  495. defaults = cls.defaults()
  496. specified = dict(
  497. (attr, getattr(dialect, attr, None))
  498. for attr in defaults
  499. if getattr(dialect, attr, None) is not None or
  500. attr in ['quotechar', 'delimiter', 'lineterminator', 'quoting']
  501. )
  502. defaults.update(specified)
  503. dialect = type(str('CombinedDialect'), (cls,), defaults)
  504. cls.validate(dialect)
  505. return dialect()
  506. def __delattr__(self, attr):
  507. if self._valid:
  508. raise AttributeError('dialect is immutable.')
  509. super(Dialect, self).__delattr__(attr)
  510. def __setattr__(self, attr, value):
  511. if self._valid:
  512. raise AttributeError('dialect is immutable.')
  513. super(Dialect, self).__setattr__(attr, value)
  514. class Excel(Dialect):
  515. """Describe the usual properties of Excel-generated CSV files."""
  516. delimiter = ','
  517. quotechar = '"'
  518. doublequote = True
  519. skipinitialspace = False
  520. lineterminator = '\r\n'
  521. quoting = QUOTE_MINIMAL
  522. register_dialect("excel", Excel)
  523. class ExcelTab(Excel):
  524. """Describe the usual properties of Excel-generated TAB-delimited files."""
  525. delimiter = '\t'
  526. register_dialect("excel-tab", ExcelTab)
  527. class UnixDialect(Dialect):
  528. """Describe the usual properties of Unix-generated CSV files."""
  529. delimiter = ','
  530. quotechar = '"'
  531. doublequote = True
  532. skipinitialspace = False
  533. lineterminator = '\n'
  534. quoting = QUOTE_ALL
  535. register_dialect("unix", UnixDialect)
  536. class DictReader(object):
  537. def __init__(self, f, fieldnames=None, restkey=None, restval=None,
  538. *args, **kwds):
  539. self._fieldnames = fieldnames # list of keys for the dict
  540. self.restkey = restkey # key to catch long rows
  541. self.restval = restval # default value for short rows
  542. self.dialect = kwds.get('dialect', "excel")
  543. self.reader = Reader(f, self.dialect, *args, **kwds)
  544. self.line_num = 0
  545. def __iter__(self):
  546. return self
  547. @property
  548. def fieldnames(self):
  549. if self._fieldnames is None:
  550. try:
  551. self._fieldnames = next(self.reader)
  552. except StopIteration:
  553. pass
  554. self.line_num = self.reader.line_num
  555. return self._fieldnames
  556. @fieldnames.setter
  557. def fieldnames(self, value):
  558. self._fieldnames = value
  559. def __next__(self):
  560. if self.line_num == 0:
  561. # Used only for its side effect.
  562. self.fieldnames
  563. row = next(self.reader)
  564. self.line_num = self.reader.line_num
  565. # unlike the basic reader, we prefer not to return blanks,
  566. # because we will typically wind up with a dict full of None
  567. # values
  568. while row == []:
  569. row = next(self.reader)
  570. d = dict(zip(self.fieldnames, row))
  571. lf = len(self.fieldnames)
  572. lr = len(row)
  573. if lf < lr:
  574. d[self.restkey] = row[lf:]
  575. elif lf > lr:
  576. for key in self.fieldnames[lr:]:
  577. d[key] = self.restval
  578. return d
  579. next = __next__
  580. class DictWriter(object):
  581. def __init__(self, f, fieldnames, *args, **kwds):
  582. self.fieldnames = fieldnames # list of keys for the dict
  583. self.extrasaction = kwds.get('extrasaction', "raise")
  584. self.restval = kwds.get('restval', "") # for writing short dicts
  585. if self.extrasaction.lower() not in ("raise", "ignore"):
  586. raise ValueError("extrasaction (%s) must be 'raise' or 'ignore'"
  587. % self.extrasaction)
  588. dialect = kwds.get('dialect', "excel")
  589. self.Writer = Writer(f, dialect, *args, **kwds)
  590. def writeheader(self):
  591. header = dict(zip(self.fieldnames, self.fieldnames))
  592. self.writerow(header)
  593. def _dict_to_list(self, rowdict):
  594. if self.extrasaction == "raise":
  595. wrong_fields = [k for k in rowdict if k not in self.fieldnames]
  596. if wrong_fields:
  597. raise ValueError("dict contains fields not in fieldnames: " +
  598. ", ".join([repr(x) for x in wrong_fields]))
  599. return (rowdict.get(key, self.restval) for key in self.fieldnames)
  600. def writerow(self, rowdict):
  601. return self.Writer.writerow(self._dict_to_list(rowdict))
  602. def writerows(self, rowdicts):
  603. return self.Writer.writerows(map(self._dict_to_list, rowdicts))
上海开阖软件有限公司 沪ICP备12045867号-1