PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/lib_pypy/_csv.py

https://bitbucket.org/dac_io/pypy
Python | 572 lines | 546 code | 3 blank | 23 comment | 4 complexity | b19c93224b189fdef3e5be2f83f4e073 MD5 | raw file
  1. """CSV parsing and writing.
  2. This module provides classes that assist in the reading and writing
  3. of Comma Separated Value (CSV) files, and implements the interface
  4. described by PEP 305. Although many CSV files are simple to parse,
  5. the format is not formally defined by a stable specification and
  6. is subtle enough that parsing lines of a CSV file with something
  7. like line.split(\",\") is bound to fail. The module supports three
  8. basic APIs: reading, writing, and registration of dialects.
  9. DIALECT REGISTRATION:
  10. Readers and writers support a dialect argument, which is a convenient
  11. handle on a group of settings. When the dialect argument is a string,
  12. it identifies one of the dialects previously registered with the module.
  13. If it is a class or instance, the attributes of the argument are used as
  14. the settings for the reader or writer:
  15. class excel:
  16. delimiter = ','
  17. quotechar = '\"'
  18. escapechar = None
  19. doublequote = True
  20. skipinitialspace = False
  21. lineterminator = '\\r\\n'
  22. quoting = QUOTE_MINIMAL
  23. SETTINGS:
  24. * quotechar - specifies a one-character string to use as the
  25. quoting character. It defaults to '\"'.
  26. * delimiter - specifies a one-character string to use as the
  27. field separator. It defaults to ','.
  28. * skipinitialspace - specifies how to interpret whitespace which
  29. immediately follows a delimiter. It defaults to False, which
  30. means that whitespace immediately following a delimiter is part
  31. of the following field.
  32. * lineterminator - specifies the character sequence which should
  33. terminate rows.
  34. * quoting - controls when quotes should be generated by the writer.
  35. It can take on any of the following module constants:
  36. csv.QUOTE_MINIMAL means only when required, for example, when a
  37. field contains either the quotechar or the delimiter
  38. csv.QUOTE_ALL means that quotes are always placed around fields.
  39. csv.QUOTE_NONNUMERIC means that quotes are always placed around
  40. fields which do not parse as integers or floating point
  41. numbers.
  42. csv.QUOTE_NONE means that quotes are never placed around fields.
  43. * escapechar - specifies a one-character string used to escape
  44. the delimiter when quoting is set to QUOTE_NONE.
  45. * doublequote - controls the handling of quotes inside fields. When
  46. True, two consecutive quotes are interpreted as one during read,
  47. and when writing, each quote character embedded in the data is
  48. written as two quotes.
  49. """
  50. __version__ = "1.0"
  51. QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4)
  52. _dialects = {}
  53. _field_limit = 128 * 1024 # max parsed field size
  54. class Error(Exception):
  55. pass
  56. class Dialect(object):
  57. """CSV dialect
  58. The Dialect type records CSV parsing and generation options."""
  59. __slots__ = ["_delimiter", "_doublequote", "_escapechar",
  60. "_lineterminator", "_quotechar", "_quoting",
  61. "_skipinitialspace", "_strict"]
  62. def __new__(cls, dialect, **kwargs):
  63. for name in kwargs:
  64. if '_' + name not in Dialect.__slots__:
  65. raise TypeError("unexpected keyword argument '%s'" %
  66. (name,))
  67. if dialect is not None:
  68. if isinstance(dialect, basestring):
  69. dialect = get_dialect(dialect)
  70. # Can we reuse this instance?
  71. if (isinstance(dialect, Dialect)
  72. and all(value is None for value in kwargs.itervalues())):
  73. return dialect
  74. self = object.__new__(cls)
  75. def set_char(x):
  76. if x is None:
  77. return None
  78. if isinstance(x, str) and len(x) <= 1:
  79. return x
  80. raise TypeError("%r must be a 1-character string" % (name,))
  81. def set_str(x):
  82. if isinstance(x, str):
  83. return x
  84. raise TypeError("%r must be a string" % (name,))
  85. def set_quoting(x):
  86. if x in range(4):
  87. return x
  88. raise TypeError("bad 'quoting' value")
  89. attributes = {"delimiter": (',', set_char),
  90. "doublequote": (True, bool),
  91. "escapechar": (None, set_char),
  92. "lineterminator": ("\r\n", set_str),
  93. "quotechar": ('"', set_char),
  94. "quoting": (QUOTE_MINIMAL, set_quoting),
  95. "skipinitialspace": (False, bool),
  96. "strict": (False, bool),
  97. }
  98. # Copy attributes
  99. notset = object()
  100. for name in Dialect.__slots__:
  101. name = name[1:]
  102. value = notset
  103. if name in kwargs:
  104. value = kwargs[name]
  105. elif dialect is not None:
  106. value = getattr(dialect, name, notset)
  107. # mapping by name: (default, converter)
  108. if value is notset:
  109. value = attributes[name][0]
  110. if name == 'quoting' and not self.quotechar:
  111. value = QUOTE_NONE
  112. else:
  113. converter = attributes[name][1]
  114. if converter:
  115. value = converter(value)
  116. setattr(self, '_' + name, value)
  117. if not self.delimiter:
  118. raise TypeError("delimiter must be set")
  119. if self.quoting != QUOTE_NONE and not self.quotechar:
  120. raise TypeError("quotechar must be set if quoting enabled")
  121. if not self.lineterminator:
  122. raise TypeError("lineterminator must be set")
  123. return self
  124. delimiter = property(lambda self: self._delimiter)
  125. doublequote = property(lambda self: self._doublequote)
  126. escapechar = property(lambda self: self._escapechar)
  127. lineterminator = property(lambda self: self._lineterminator)
  128. quotechar = property(lambda self: self._quotechar)
  129. quoting = property(lambda self: self._quoting)
  130. skipinitialspace = property(lambda self: self._skipinitialspace)
  131. strict = property(lambda self: self._strict)
  132. def _call_dialect(dialect_inst, kwargs):
  133. return Dialect(dialect_inst, **kwargs)
  134. def register_dialect(name, dialect=None, **kwargs):
  135. """Create a mapping from a string name to a dialect class.
  136. dialect = csv.register_dialect(name, dialect)"""
  137. if not isinstance(name, basestring):
  138. raise TypeError("dialect name must be a string or unicode")
  139. dialect = _call_dialect(dialect, kwargs)
  140. _dialects[name] = dialect
  141. def unregister_dialect(name):
  142. """Delete the name/dialect mapping associated with a string name.\n
  143. csv.unregister_dialect(name)"""
  144. try:
  145. del _dialects[name]
  146. except KeyError:
  147. raise Error("unknown dialect")
  148. def get_dialect(name):
  149. """Return the dialect instance associated with name.
  150. dialect = csv.get_dialect(name)"""
  151. try:
  152. return _dialects[name]
  153. except KeyError:
  154. raise Error("unknown dialect")
  155. def list_dialects():
  156. """Return a list of all know dialect names
  157. names = csv.list_dialects()"""
  158. return list(_dialects)
  159. class Reader(object):
  160. """CSV reader
  161. Reader objects are responsible for reading and parsing tabular data
  162. in CSV format."""
  163. (START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
  164. IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
  165. EAT_CRNL) = range(8)
  166. def __init__(self, iterator, dialect=None, **kwargs):
  167. self.dialect = _call_dialect(dialect, kwargs)
  168. self.input_iter = iter(iterator)
  169. self.line_num = 0
  170. self._parse_reset()
  171. def _parse_reset(self):
  172. self.field = ''
  173. self.fields = []
  174. self.state = self.START_RECORD
  175. self.numeric_field = False
  176. def __iter__(self):
  177. return self
  178. def next(self):
  179. self._parse_reset()
  180. while True:
  181. try:
  182. line = self.input_iter.next()
  183. except StopIteration:
  184. # End of input OR exception
  185. if len(self.field) > 0:
  186. raise Error("newline inside string")
  187. raise
  188. self.line_num += 1
  189. if '\0' in line:
  190. raise Error("line contains NULL byte")
  191. pos = 0
  192. while pos < len(line):
  193. pos = self._parse_process_char(line, pos)
  194. self._parse_eol()
  195. if self.state == self.START_RECORD:
  196. break
  197. fields = self.fields
  198. self.fields = []
  199. return fields
  200. def _parse_process_char(self, line, pos):
  201. c = line[pos]
  202. if self.state == self.IN_FIELD:
  203. # in unquoted field
  204. pos2 = pos
  205. while True:
  206. if c in '\n\r':
  207. # end of line - return [fields]
  208. if pos2 > pos:
  209. self._parse_add_char(line[pos:pos2])
  210. pos = pos2
  211. self._parse_save_field()
  212. self.state = self.EAT_CRNL
  213. elif c == self.dialect.escapechar:
  214. # possible escaped character
  215. pos2 -= 1
  216. self.state = self.ESCAPED_CHAR
  217. elif c == self.dialect.delimiter:
  218. # save field - wait for new field
  219. if pos2 > pos:
  220. self._parse_add_char(line[pos:pos2])
  221. pos = pos2
  222. self._parse_save_field()
  223. self.state = self.START_FIELD
  224. else:
  225. # normal character - save in field
  226. pos2 += 1
  227. if pos2 < len(line):
  228. c = line[pos2]
  229. continue
  230. break
  231. if pos2 > pos:
  232. self._parse_add_char(line[pos:pos2])
  233. pos = pos2 - 1
  234. elif self.state == self.START_RECORD:
  235. if c in '\n\r':
  236. self.state = self.EAT_CRNL
  237. else:
  238. self.state = self.START_FIELD
  239. # restart process
  240. self._parse_process_char(line, pos)
  241. elif self.state == self.START_FIELD:
  242. if c in '\n\r':
  243. # save empty field - return [fields]
  244. self._parse_save_field()
  245. self.state = self.EAT_CRNL
  246. elif (c == self.dialect.quotechar
  247. and self.dialect.quoting != QUOTE_NONE):
  248. # start quoted field
  249. self.state = self.IN_QUOTED_FIELD
  250. elif c == self.dialect.escapechar:
  251. # possible escaped character
  252. self.state = self.ESCAPED_CHAR
  253. elif c == ' ' and self.dialect.skipinitialspace:
  254. # ignore space at start of field
  255. pass
  256. elif c == self.dialect.delimiter:
  257. # save empty field
  258. self._parse_save_field()
  259. else:
  260. # begin new unquoted field
  261. if self.dialect.quoting == QUOTE_NONNUMERIC:
  262. self.numeric_field = True
  263. self._parse_add_char(c)
  264. self.state = self.IN_FIELD
  265. elif self.state == self.ESCAPED_CHAR:
  266. self._parse_add_char(c)
  267. self.state = self.IN_FIELD
  268. elif self.state == self.IN_QUOTED_FIELD:
  269. if c == self.dialect.escapechar:
  270. # possible escape character
  271. self.state = self.ESCAPE_IN_QUOTED_FIELD
  272. elif (c == self.dialect.quotechar
  273. and self.dialect.quoting != QUOTE_NONE):
  274. if self.dialect.doublequote:
  275. # doublequote; " represented by ""
  276. self.state = self.QUOTE_IN_QUOTED_FIELD
  277. else:
  278. #end of quote part of field
  279. self.state = self.IN_FIELD
  280. else:
  281. # normal character - save in field
  282. self._parse_add_char(c)
  283. elif self.state == self.ESCAPE_IN_QUOTED_FIELD:
  284. self._parse_add_char(c)
  285. self.state = self.IN_QUOTED_FIELD
  286. elif self.state == self.QUOTE_IN_QUOTED_FIELD:
  287. # doublequote - seen a quote in a quoted field
  288. if (c == self.dialect.quotechar
  289. and self.dialect.quoting != QUOTE_NONE):
  290. # save "" as "
  291. self._parse_add_char(c)
  292. self.state = self.IN_QUOTED_FIELD
  293. elif c == self.dialect.delimiter:
  294. # save field - wait for new field
  295. self._parse_save_field()
  296. self.state = self.START_FIELD
  297. elif c in '\r\n':
  298. # end of line - return [fields]
  299. self._parse_save_field()
  300. self.state = self.EAT_CRNL
  301. elif not self.dialect.strict:
  302. self._parse_add_char(c)
  303. self.state = self.IN_FIELD
  304. else:
  305. raise Error("'%c' expected after '%c'" %
  306. (self.dialect.delimiter, self.dialect.quotechar))
  307. elif self.state == self.EAT_CRNL:
  308. if c in '\r\n':
  309. pass
  310. else:
  311. raise Error("new-line character seen in unquoted field - "
  312. "do you need to open the file "
  313. "in universal-newline mode?")
  314. else:
  315. raise RuntimeError("unknown state: %r" % (self.state,))
  316. return pos + 1
  317. def _parse_eol(self):
  318. if self.state == self.EAT_CRNL:
  319. self.state = self.START_RECORD
  320. elif self.state == self.START_RECORD:
  321. # empty line - return []
  322. pass
  323. elif self.state == self.IN_FIELD:
  324. # in unquoted field
  325. # end of line - return [fields]
  326. self._parse_save_field()
  327. self.state = self.START_RECORD
  328. elif self.state == self.START_FIELD:
  329. # save empty field - return [fields]
  330. self._parse_save_field()
  331. self.state = self.START_RECORD
  332. elif self.state == self.ESCAPED_CHAR:
  333. self._parse_add_char('\n')
  334. self.state = self.IN_FIELD
  335. elif self.state == self.IN_QUOTED_FIELD:
  336. pass
  337. elif self.state == self.ESCAPE_IN_QUOTED_FIELD:
  338. self._parse_add_char('\n')
  339. self.state = self.IN_QUOTED_FIELD
  340. elif self.state == self.QUOTE_IN_QUOTED_FIELD:
  341. # end of line - return [fields]
  342. self._parse_save_field()
  343. self.state = self.START_RECORD
  344. else:
  345. raise RuntimeError("unknown state: %r" % (self.state,))
  346. def _parse_save_field(self):
  347. field, self.field = self.field, ''
  348. if self.numeric_field:
  349. self.numeric_field = False
  350. field = float(field)
  351. self.fields.append(field)
  352. def _parse_add_char(self, c):
  353. if len(self.field) + len(c) > _field_limit:
  354. raise Error("field larger than field limit (%d)" % (_field_limit))
  355. self.field += c
  356. class Writer(object):
  357. """CSV writer
  358. Writer objects are responsible for generating tabular data
  359. in CSV format from sequence input."""
  360. def __init__(self, file, dialect=None, **kwargs):
  361. if not (hasattr(file, 'write') and callable(file.write)):
  362. raise TypeError("argument 1 must have a 'write' method")
  363. self.writeline = file.write
  364. self.dialect = _call_dialect(dialect, kwargs)
  365. def _join_reset(self):
  366. self.rec = []
  367. self.num_fields = 0
  368. def _join_append(self, field, quoted, quote_empty):
  369. dialect = self.dialect
  370. # If this is not the first field we need a field separator
  371. if self.num_fields > 0:
  372. self.rec.append(dialect.delimiter)
  373. if dialect.quoting == QUOTE_NONE:
  374. need_escape = tuple(dialect.lineterminator) + (
  375. dialect.escapechar, # escapechar always first
  376. dialect.delimiter, dialect.quotechar)
  377. else:
  378. for c in tuple(dialect.lineterminator) + (
  379. dialect.delimiter, dialect.escapechar):
  380. if c and c in field:
  381. quoted = True
  382. need_escape = ()
  383. if dialect.quotechar in field:
  384. if dialect.doublequote:
  385. field = field.replace(dialect.quotechar,
  386. dialect.quotechar * 2)
  387. quoted = True
  388. else:
  389. need_escape = (dialect.quotechar,)
  390. for c in need_escape:
  391. if c and c in field:
  392. if not dialect.escapechar:
  393. raise Error("need to escape, but no escapechar set")
  394. field = field.replace(c, dialect.escapechar + c)
  395. # If field is empty check if it needs to be quoted
  396. if field == '' and quote_empty:
  397. if dialect.quoting == QUOTE_NONE:
  398. raise Error("single empty field record must be quoted")
  399. quoted = 1
  400. if quoted:
  401. field = dialect.quotechar + field + dialect.quotechar
  402. self.rec.append(field)
  403. self.num_fields += 1
  404. def writerow(self, row):
  405. dialect = self.dialect
  406. try:
  407. rowlen = len(row)
  408. except TypeError:
  409. raise Error("sequence expected")
  410. # join all fields in internal buffer
  411. self._join_reset()
  412. for field in row:
  413. quoted = False
  414. if dialect.quoting == QUOTE_NONNUMERIC:
  415. try:
  416. float(field)
  417. except:
  418. quoted = True
  419. # This changed since 2.5:
  420. # quoted = not isinstance(field, (int, long, float))
  421. elif dialect.quoting == QUOTE_ALL:
  422. quoted = True
  423. if field is None:
  424. self._join_append("", quoted, rowlen == 1)
  425. else:
  426. self._join_append(str(field), quoted, rowlen == 1)
  427. # add line terminator
  428. self.rec.append(dialect.lineterminator)
  429. self.writeline(''.join(self.rec))
  430. def writerows(self, rows):
  431. for row in rows:
  432. self.writerow(row)
  433. def reader(*args, **kwargs):
  434. """
  435. csv_reader = reader(iterable [, dialect='excel']
  436. [optional keyword args])
  437. for row in csv_reader:
  438. process(row)
  439. The "iterable" argument can be any object that returns a line
  440. of input for each iteration, such as a file object or a list. The
  441. optional \"dialect\" parameter is discussed below. The function
  442. also accepts optional keyword arguments which override settings
  443. provided by the dialect.
  444. The returned object is an iterator. Each iteration returns a row
  445. of the CSV file (which can span multiple input lines)"""
  446. return Reader(*args, **kwargs)
  447. def writer(*args, **kwargs):
  448. """
  449. csv_writer = csv.writer(fileobj [, dialect='excel']
  450. [optional keyword args])
  451. for row in sequence:
  452. csv_writer.writerow(row)
  453. [or]
  454. csv_writer = csv.writer(fileobj [, dialect='excel']
  455. [optional keyword args])
  456. csv_writer.writerows(rows)
  457. The \"fileobj\" argument can be any object that supports the file API."""
  458. return Writer(*args, **kwargs)
  459. undefined = object()
  460. def field_size_limit(limit=undefined):
  461. """Sets an upper limit on parsed fields.
  462. csv.field_size_limit([limit])
  463. Returns old limit. If limit is not given, no new limit is set and
  464. the old limit is returned"""
  465. global _field_limit
  466. old_limit = _field_limit
  467. if limit is not undefined:
  468. if not isinstance(limit, (int, long)):
  469. raise TypeError("int expected, got %s" %
  470. (limit.__class__.__name__,))
  471. _field_limit = limit
  472. return old_limit