使用`line-seq`和`reader`,什么时候文件关闭? [英] Using `line-seq` with `reader`, when is the file closed?

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

问题描述

我正在使用(line-seq(readerinput.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(readerinput.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-seq 阅读器文件?是否有不同的模式我应该在这里?

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,这取决于我的程序返回和/或我的程序是否懒惰地消耗序列。

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天全站免登陆