Using `line-seq` with` reader` when the file is closed?

I am reading lines from a text file using (line-seq (reader "input.txt")) . Then this collection is transferred and used by my program.

I am worried that this may be a bad style, as I am not deterministically closing the file. I suppose I can't use (with-open (line-seq (reader "input.txt"))) , since the file stream will potentially be closed before I go through the whole sequence.

Should lazy-seq combined with reader for files? Is there any other template that I should use here?

+6
source share
2 answers

Since this one doesn’t really have a clear answer (all this mixes up with the comments for the first answer), here is its essence:

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

This will force the entire line of lines to read and close the file. Then you can pass the result of all this expression.

When working with large files, you may have problems with memory (saving the entire sequence of lines in memory) and that if it is recommended to invert the program:

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

In this case, you may or may not need to, depending on what my program returns and / or my program consumes a sequence lazily or not.

+15
source

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

0
source

Source: https://habr.com/ru/post/892247/


All Articles