I’m porting some of my python scripts to Common Lisp. I need to get list of files in some directory and print each file’s content by lines.
This code shows me all filenames. But lines are printed only for last file. Why?
Also, what is the best way ti iterate by file lines?
Thanks.
(dolist (file (directory (make-pathname :name :wild
:type :wild
:defaults "path\\to\\files\\")))
(print file)
(with-open-file (stream file)
(do ((line (read-line stream) (read-line stream)))
(nil t)
(print line))))
I would propose to write a function which prints a file given a pathname and a stream.
You iterate with
DO. That’s okay, but I would use something likeLOOPwhich allows slightly easier to read code.Your
DOis an endless loop. You might want to end the loop when the EOF is reached.READ-LINEgenerates an error when it reads past the end of the file. Thus your code signals an error on the end of the first file. This error causes your code to only print the first file.You need to call
READ-LINEsuch a way that you test for EOF and end the iteration then. See the arguments toREAD-LINE. Alternatively you can catch the EOF error, but the other solution is slightly easier.