且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Clojure中的文件读取n行

更新时间:2023-08-26 18:27:04

您的代码会产生边界错误,因为您在同一阅读器上多次调用 line-seq 。如果要从阅读器中获取许多行,则应该只调用一次 line-seq ,然后从该序列中获取所需的行数:

Your code produces an out-of-bounds error because you call line-seq multiple times on the same reader. If you want to get a number of lines from a reader, you should call line-seq only once, then take the desired number of lines from that sequence:

(require '[clojure.java.io :as io])

(defn lines [n filename]
  (with-open [rdr (io/reader filename)]
    (doall (take n (line-seq rdr)))))

示例:

(run! println (lines 20 "test.txt"))

如果 test.txt 包含少于20行,这将只打印文件中的所有行。

If test.txt contains fewer than 20 lines, this will simply print all the lines in the file.