将“line-seq"与“reader"一起使用,文件何时关闭? [英] Using `line-seq` with `reader`, when is the file closed?

查看:24
本文介绍了将“line-seq"与“reader"一起使用,文件何时关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

应该避免将 lazy-seqreader 一起用于文件吗?我应该在这里使用不同的模式吗?

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

推荐答案

由于这个没有真正明确的答案(在第一个答案的评论中都混入了),所以这里是它的本质:

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))))

在这种情况下,您可能需要也可能不需要 doall,这取决于 my-program 返回的内容和/或 my-program 是否懒惰地使用序列.

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.

这篇关于将“line-seq"与“reader"一起使用,文件何时关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆