使用 Scala 分割大型 CSV 文件

发布于 2024-09-17 08:37:07 字数 103 浏览 5 评论 0原文

在 Scala 2.8 中进行文件 IO 的最佳方法是什么?

我想要做的就是将一个巨大的 CSV 文件切成许多较小的文件,例如每个文件 1000 行数据,并且每个文件保留标题。

What's the best way to do file IO in Scala 2.8?

All I want to do is cut a massive CSV file into lots of smaller ones with, say 1000 lines of data per file, and each file retaining the header.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

余厌 2024-09-24 08:37:07

对于像这样的简单任务,我会使用 scala.io.Source 。一个例子如下:

val input = io.Source.fromFile("input.csv").getLines()

if (input.hasNext) {
  // assuming one header line
  val header = List(input.next())

  for ((i, lines) <- Iterator.from(1) zip input.grouped(linesPerFile)) {
    val out = createWriter(i) // Create a file for index i
    (header.iterator ++ lines.iterator).foreach(out.println)
    out.close
  }
}

For simple tasks like this I would use scala.io.Source. An example would look like this:

val input = io.Source.fromFile("input.csv").getLines()

if (input.hasNext) {
  // assuming one header line
  val header = List(input.next())

  for ((i, lines) <- Iterator.from(1) zip input.grouped(linesPerFile)) {
    val out = createWriter(i) // Create a file for index i
    (header.iterator ++ lines.iterator).foreach(out.println)
    out.close
  }
}
别想她 2024-09-24 08:37:07

Moritz 的答案很好,只要您没有遇到 CSV 的一些更烦人的极端情况。一个相关的示例是 CSV 数据,其中一列是可能包含换行符的字符串:您不能依赖一行位于一行上,否则您最终会将某些行切成两半。

我会使用专用的 CSV 解析库将您的数据转换为迭代器。 kantan.csv 是一个示例(我是作者),但还有其他选择,例如产品集合opencsv

Moritz' answer is good, provided you don't run into some of CSV's more annoying corner cases. A relevant example would be CSV data where one column is a string that might contain line breaks: you can't rely on a row being on a single line, or you'll end up cutting some rows in half.

I'd use a dedicated CSV parsing library to turn your data into an iterator. kantan.csv is an example (I'm the author), but there are other alternatives such as product-collections or opencsv.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文