Nim 语言读取 csv 文件

285 阅读2分钟

Nim编程早茶

这一节,我们来介绍,如何使用 Nim 读取 CSV 文件。我们使用标准库中的 parseCsv 模块,如果对数据处理有需求,也可以使用第三方库 nimdata 来读取 csv 文件。

csv 文本中没有 header

以下 csv 文件中没有 header,分隔使用 ,,注意 , 后面不能有空格。当我们使用三引号的时候,要注意每一行文本后面其实是有 \n 字符的。

readRow 用来读取每一行的内容,如果读到文本末尾将会返回 false。要注意,readRow 会忽略空白行。

import parsecsv


let textWithoutHeader = """1,2,3
4,5,6

7,8,9
"""
writeFile("text_without_header.txt", textWithoutHeader)
var p: CsvParser
p.open("text_without_header.txt")
while p.readRow:
  echo "新一行: "
  for value in items(p.row):
    stdout.write value, " " 
  echo ""
p.close()

可以看到,只输出了三行,空白行被忽略了。

新一行:
1 2 3
新一行:
4 5 6
新一行:
7 8 9

csv 文本中有 header

对于含有 header 的 csv 文件,我们需要先使用 readHeaderRow 读取首行内容,然后这些列名,将会存储在 headers 属性中。我们调用 rowEntry 函数,可以访问当前行对应列的元素。

let textWithHeader = """one, two, three 
1,2,3
4,5,6
7,8,9
"""
writeFile("text_with_header.txt", textWithHeader)
var p: CsvParser
p.open("text_with_header.txt")
p.readHeaderRow()
while p.readRow:
  echo "新一行: "
  for col in items(p.headers):
    stdout.write(col, "->", p.rowEntry(col), " ")
  echo ""
p.close()

输出:

新一行:
one->1  two->2  three ->3
新一行:
one->4  two->5  three ->6
新一行:
one->7  two->8  three ->9

csv 文本中分隔符之后允许有空格

对于 csv 文本中分隔符之后存在空格,我们可以使用 skipInitialSpace=true 来忽略空格。我们还可以更改分隔符 separator='&'

let textWithSpace = """one, two, three 
1&   2&3
4&  5& 6
7& 8&9
"""
writeFile("text_with_space.txt", textWithSpace)
var p: CsvParser
p.open("text_with_space.txt", separator='&', skipInitialSpace=true)
p.readHeaderRow()
while p.readRow:
  echo "新一行: "
  for col in items(p.headers):
    stdout.write(col, "->", p.rowEntry(col), " ")
  echo ""
p.close()

输出:

新一行:
one->1 two->2 three ->3
新一行:
one->4 two->5 three ->6
新一行:
one->7 two->8 three ->9

文本中有字符串

默认是去除文本中的引号的,我们也可以禁用这一功能,设置 quote = '\x00'

let textWithString = """one, two, three 
"1","2","3"
"4","5","6"
"7","8","9"
"""
writeFile("text_with_string.txt", textWithString)
var p: CsvParser
p.open("text_with_string.txt", quote='\x00')
p.readHeaderRow()
while p.readRow:
  echo "新一行: "
  for col in items(p.headers):
    stdout.write(col, "->", p.rowEntry(col), " ")
  echo ""
p.close()

默认情况,输出(quote='"')

新一行:
one->1  two->2  three ->3
新一行:
one->4  two->5  three ->6
新一行:
one->7  two->8  three ->9

输出(quote='\x00')

新一行:
one->"1"  two->"2"  three ->"3"
新一行:
one->"4"  two->"5"  three ->"6"
新一行:
one->"7"  two->"8"  three ->"9"