parsecsv.nim 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2009 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements a simple high performance `CSV`:idx:
  10. ## (`comma separated value`:idx:) parser.
  11. ##
  12. ## Basic usage
  13. ## ===========
  14. ##
  15. ## .. code-block:: nim
  16. ## import std/parsecsv
  17. ## from std/os import paramStr
  18. ## from std/streams import newFileStream
  19. ##
  20. ## var s = newFileStream(paramStr(1), fmRead)
  21. ## if s == nil:
  22. ## quit("cannot open the file" & paramStr(1))
  23. ##
  24. ## var x: CsvParser
  25. ## open(x, s, paramStr(1))
  26. ## while readRow(x):
  27. ## echo "new row: "
  28. ## for val in items(x.row):
  29. ## echo "##", val, "##"
  30. ## close(x)
  31. ##
  32. ## For CSV files with a header row, the header can be read and then used as a
  33. ## reference for item access with `rowEntry <#rowEntry,CsvParser,string>`_:
  34. ##
  35. ## .. code-block:: nim
  36. ## import std/parsecsv
  37. ##
  38. ## # Prepare a file
  39. ## let content = """One,Two,Three,Four
  40. ## 1,2,3,4
  41. ## 10,20,30,40
  42. ## 100,200,300,400
  43. ## """
  44. ## writeFile("temp.csv", content)
  45. ##
  46. ## var p: CsvParser
  47. ## p.open("temp.csv")
  48. ## p.readHeaderRow()
  49. ## while p.readRow():
  50. ## echo "new row: "
  51. ## for col in items(p.headers):
  52. ## echo "##", col, ":", p.rowEntry(col), "##"
  53. ## p.close()
  54. ##
  55. ## See also
  56. ## ========
  57. ##
  58. ## * `streams module <streams.html>`_ for using
  59. ## `open proc <#open,CsvParser,Stream,string,char,char,char>`_
  60. ## and other stream processing (like `close proc <streams.html#close,Stream>`_)
  61. ## * `parseopt module <parseopt.html>`_ for a command line parser
  62. ## * `parsecfg module <parsecfg.html>`_ for a configuration file parser
  63. ## * `parsexml module <parsexml.html>`_ for a XML / HTML parser
  64. ## * `parsesql module <parsesql.html>`_ for a SQL parser
  65. ## * `other parsers <lib.html#pure-libraries-parsers>`_ for other parsers
  66. import lexbase, streams
  67. when defined(nimPreviewSlimSystem):
  68. import std/syncio
  69. type
  70. CsvRow* = seq[string] ## A row in a CSV file.
  71. CsvParser* = object of BaseLexer ## The parser object.
  72. ##
  73. ## It consists of two public fields:
  74. ## * `row` is the current row
  75. ## * `headers` are the columns that are defined in the csv file
  76. ## (read using `readHeaderRow <#readHeaderRow,CsvParser>`_).
  77. ## Used with `rowEntry <#rowEntry,CsvParser,string>`_).
  78. row*: CsvRow
  79. filename: string
  80. sep, quote, esc: char
  81. skipWhite: bool
  82. currRow: int
  83. headers*: seq[string]
  84. CsvError* = object of IOError ## An exception that is raised if
  85. ## a parsing error occurs.
  86. proc raiseEInvalidCsv(filename: string, line, col: int,
  87. msg: string) {.noreturn.} =
  88. var e: ref CsvError
  89. new(e)
  90. if filename.len == 0:
  91. e.msg = "Error: " & msg
  92. else:
  93. e.msg = filename & "(" & $line & ", " & $col & ") Error: " & msg
  94. raise e
  95. proc error(self: CsvParser, pos: int, msg: string) =
  96. raiseEInvalidCsv(self.filename, self.lineNumber, getColNumber(self, pos), msg)
  97. proc open*(self: var CsvParser, input: Stream, filename: string,
  98. separator = ',', quote = '"', escape = '\0',
  99. skipInitialSpace = false) =
  100. ## Initializes the parser with an input stream. `Filename` is only used
  101. ## for nice error messages. The parser's behaviour can be controlled by
  102. ## the diverse optional parameters:
  103. ## - `separator`: character used to separate fields
  104. ## - `quote`: Used to quote fields containing special characters like
  105. ## `separator`, `quote` or new-line characters. '\\0' disables the parsing
  106. ## of quotes.
  107. ## - `escape`: removes any special meaning from the following character;
  108. ## '\\0' disables escaping; if escaping is disabled and `quote` is not '\\0',
  109. ## two `quote` characters are parsed one literal `quote` character.
  110. ## - `skipInitialSpace`: If true, whitespace immediately following the
  111. ## `separator` is ignored.
  112. ##
  113. ## See also:
  114. ## * `open proc <#open,CsvParser,string,char,char,char>`_ which creates the
  115. ## file stream for you
  116. runnableExamples:
  117. import std/streams
  118. var strm = newStringStream("One,Two,Three\n1,2,3\n10,20,30")
  119. var parser: CsvParser
  120. parser.open(strm, "tmp.csv")
  121. parser.close()
  122. strm.close()
  123. lexbase.open(self, input)
  124. self.filename = filename
  125. self.sep = separator
  126. self.quote = quote
  127. self.esc = escape
  128. self.skipWhite = skipInitialSpace
  129. proc open*(self: var CsvParser, filename: string,
  130. separator = ',', quote = '"', escape = '\0',
  131. skipInitialSpace = false) =
  132. ## Similar to the `other open proc<#open,CsvParser,Stream,string,char,char,char>`_,
  133. ## but creates the file stream for you.
  134. runnableExamples:
  135. from std/os import removeFile
  136. writeFile("tmp.csv", "One,Two,Three\n1,2,3\n10,20,300")
  137. var parser: CsvParser
  138. parser.open("tmp.csv")
  139. parser.close()
  140. removeFile("tmp.csv")
  141. var s = newFileStream(filename, fmRead)
  142. if s == nil: self.error(0, "cannot open: " & filename)
  143. open(self, s, filename, separator,
  144. quote, escape, skipInitialSpace)
  145. proc parseField(self: var CsvParser, a: var string) =
  146. var pos = self.bufpos
  147. if self.skipWhite:
  148. while self.buf[pos] in {' ', '\t'}: inc(pos)
  149. setLen(a, 0) # reuse memory
  150. if self.buf[pos] == self.quote and self.quote != '\0':
  151. inc(pos)
  152. while true:
  153. let c = self.buf[pos]
  154. if c == '\0':
  155. self.bufpos = pos # can continue after exception?
  156. error(self, pos, self.quote & " expected")
  157. break
  158. elif c == self.quote:
  159. if self.esc == '\0' and self.buf[pos + 1] == self.quote:
  160. add(a, self.quote)
  161. inc(pos, 2)
  162. else:
  163. inc(pos)
  164. break
  165. elif c == self.esc:
  166. add(a, self.buf[pos + 1])
  167. inc(pos, 2)
  168. else:
  169. case c
  170. of '\c':
  171. pos = handleCR(self, pos)
  172. add(a, "\n")
  173. of '\l':
  174. pos = handleLF(self, pos)
  175. add(a, "\n")
  176. else:
  177. add(a, c)
  178. inc(pos)
  179. else:
  180. while true:
  181. let c = self.buf[pos]
  182. if c == self.sep: break
  183. if c in {'\c', '\l', '\0'}: break
  184. add(a, c)
  185. inc(pos)
  186. self.bufpos = pos
  187. proc processedRows*(self: var CsvParser): int {.inline.} =
  188. ## Returns number of the processed rows.
  189. ##
  190. ## But even if `readRow <#readRow,CsvParser,int>`_ arrived at EOF then
  191. ## processed rows counter is incremented.
  192. runnableExamples:
  193. import std/streams
  194. var strm = newStringStream("One,Two,Three\n1,2,3")
  195. var parser: CsvParser
  196. parser.open(strm, "tmp.csv")
  197. doAssert parser.readRow()
  198. doAssert parser.processedRows() == 1
  199. doAssert parser.readRow()
  200. doAssert parser.processedRows() == 2
  201. ## Even if `readRow` arrived at EOF then `processedRows` is incremented.
  202. doAssert parser.readRow() == false
  203. doAssert parser.processedRows() == 3
  204. doAssert parser.readRow() == false
  205. doAssert parser.processedRows() == 4
  206. parser.close()
  207. strm.close()
  208. self.currRow
  209. proc readRow*(self: var CsvParser, columns = 0): bool =
  210. ## Reads the next row; if `columns` > 0, it expects the row to have
  211. ## exactly this many columns. Returns false if the end of the file
  212. ## has been encountered else true.
  213. ##
  214. ## Blank lines are skipped.
  215. runnableExamples:
  216. import std/streams
  217. var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30")
  218. var parser: CsvParser
  219. parser.open(strm, "tmp.csv")
  220. doAssert parser.readRow()
  221. doAssert parser.row == @["One", "Two", "Three"]
  222. doAssert parser.readRow()
  223. doAssert parser.row == @["1", "2", "3"]
  224. ## Blank lines are skipped.
  225. doAssert parser.readRow()
  226. doAssert parser.row == @["10", "20", "30"]
  227. var emptySeq: seq[string]
  228. doAssert parser.readRow() == false
  229. doAssert parser.row == emptySeq
  230. doAssert parser.readRow() == false
  231. doAssert parser.row == emptySeq
  232. parser.close()
  233. strm.close()
  234. var col = 0 # current column
  235. let oldpos = self.bufpos
  236. # skip initial empty lines #8365
  237. while true:
  238. case self.buf[self.bufpos]
  239. of '\c': self.bufpos = handleCR(self, self.bufpos)
  240. of '\l': self.bufpos = handleLF(self, self.bufpos)
  241. else: break
  242. while self.buf[self.bufpos] != '\0':
  243. let oldlen = self.row.len
  244. if oldlen < col + 1:
  245. setLen(self.row, col + 1)
  246. self.row[col] = ""
  247. parseField(self, self.row[col])
  248. inc(col)
  249. if self.buf[self.bufpos] == self.sep:
  250. inc(self.bufpos)
  251. else:
  252. case self.buf[self.bufpos]
  253. of '\c', '\l':
  254. # skip empty lines:
  255. while true:
  256. case self.buf[self.bufpos]
  257. of '\c': self.bufpos = handleCR(self, self.bufpos)
  258. of '\l': self.bufpos = handleLF(self, self.bufpos)
  259. else: break
  260. of '\0': discard
  261. else: error(self, self.bufpos, self.sep & " expected")
  262. break
  263. setLen(self.row, col)
  264. result = col > 0
  265. if result and col != columns and columns > 0:
  266. error(self, oldpos + 1, $columns & " columns expected, but found " &
  267. $col & " columns")
  268. inc(self.currRow)
  269. proc close*(self: var CsvParser) {.inline.} =
  270. ## Closes the parser `self` and its associated input stream.
  271. lexbase.close(self)
  272. proc readHeaderRow*(self: var CsvParser) =
  273. ## Reads the first row and creates a look-up table for column numbers
  274. ## See also:
  275. ## * `rowEntry proc <#rowEntry,CsvParser,string>`_
  276. runnableExamples:
  277. import std/streams
  278. var strm = newStringStream("One,Two,Three\n1,2,3")
  279. var parser: CsvParser
  280. parser.open(strm, "tmp.csv")
  281. parser.readHeaderRow()
  282. doAssert parser.headers == @["One", "Two", "Three"]
  283. doAssert parser.row == @["One", "Two", "Three"]
  284. doAssert parser.readRow()
  285. doAssert parser.headers == @["One", "Two", "Three"]
  286. doAssert parser.row == @["1", "2", "3"]
  287. parser.close()
  288. strm.close()
  289. let present = self.readRow()
  290. if present:
  291. self.headers = self.row
  292. proc rowEntry*(self: var CsvParser, entry: string): var string =
  293. ## Accesses a specified `entry` from the current row.
  294. ##
  295. ## Assumes that `readHeaderRow <#readHeaderRow,CsvParser>`_ has already been
  296. ## called.
  297. ##
  298. ## If specified `entry` does not exist, raises KeyError.
  299. runnableExamples:
  300. import std/streams
  301. var strm = newStringStream("One,Two,Three\n1,2,3\n\n10,20,30")
  302. var parser: CsvParser
  303. parser.open(strm, "tmp.csv")
  304. ## Requires calling `readHeaderRow`.
  305. parser.readHeaderRow()
  306. doAssert parser.readRow()
  307. doAssert parser.rowEntry("One") == "1"
  308. doAssert parser.rowEntry("Two") == "2"
  309. doAssert parser.rowEntry("Three") == "3"
  310. doAssertRaises(KeyError):
  311. discard parser.rowEntry("NonexistentEntry")
  312. parser.close()
  313. strm.close()
  314. let index = self.headers.find(entry)
  315. if index >= 0:
  316. result = self.row[index]
  317. else:
  318. raise newException(KeyError, "Entry `" & entry & "` doesn't exist")
  319. when not defined(testing) and isMainModule:
  320. import os
  321. var s = newFileStream(paramStr(1), fmRead)
  322. if s == nil: quit("cannot open the file" & paramStr(1))
  323. var x: CsvParser
  324. open(x, s, paramStr(1))
  325. while readRow(x):
  326. echo "new row: "
  327. for val in items(x.row):
  328. echo "##", val, "##"
  329. close(x)