将“line-seq”与“reader”一起使用,文件何时关闭?

发布于 2024-11-18 20:08:50 字数 271 浏览 4 评论 0原文

我正在使用 (line-seq (reader "input.txt")) 从文本文件中读取行。然后这个集合被我的程序传递和使用。

然而,我担心这可能是不好的风格,因为我没有确定性地关闭文件。我想我不能使用 (with-open (line-seq (reader "input.txt"))) ,因为文件流可能会在我遍历整个序列之前关闭。

是否应该避免将“lazy-seq”与“reader”结合使用来读取文件?我应该在这里使用不同的模式吗?

I'm reading lines from a text file using (line-seq (reader "input.txt")). This collection is then passed around and used by my program.

I'm concerned that this may be bad style however, as I'm not deterministically closing the file. I imagine that I can't use (with-open (line-seq (reader "input.txt"))), as the file stream will potentially get closed before I've traversed the entire sequence.

Should lazy-seq be avoided in conjunction with reader for files? Is there a different pattern I should be using here?

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

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

发布评论

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

评论(2

人│生佛魔见 2024-11-25 20:08:50

由于这并没有真正的明确答案(它全部混合到第一个答案的注释中),因此它的本质是:

(with-open [r (reader "input.txt")]
  (doall (line-seq r)))

这将强制读取整个行序列并关闭文件。然后您可以传递整个表达式的结果。

处理大文件时,您可能会遇到内存问题(将整个行序列保留在内存中),此时最好反转程序:

(with-open [r (reader "input.txt")]
  (doall (my-program (line-seq r))))

在这种情况下,您可能需要也可能不需要 doall,具体取决于我的程序返回和/或我的程序是否延迟使用序列。

Since this doesn't really have a clear answer (it's all mixed into comments on the first answer), here's the essence of it:

(with-open [r (reader "input.txt")]
  (doall (line-seq r)))

That will force the whole sequence of lines to be read and close the file. You can then pass the result of that whole expression around.

When dealing with large files, you may have memory problems (holding the whole sequence of lines in memory) and that's when it's a good idea to invert the program:

(with-open [r (reader "input.txt")]
  (doall (my-program (line-seq r))))

You may or may not need doall in that case, depending on what my-program returns and/or whether my-program consumes the sequence lazily or not.

话少情深 2024-11-25 20:08:50

看起来像 clojure .contrib.duck-streams/read-lines 正是您所寻找的。 read-lines 在没有输入时关闭文件,并像 line-seq 一样返回序列。尝试查看read-lines的源代码。

It seems like the clojure.contrib.duck-streams/read-lines is just what you are looking for. read-lines closes the file when there is no input and returns the sequence just like line-seq. Try to look at source code of read-lines.

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