LISP - 将列表写入文件

时间:2016-07-21 14:38:39

标签: lisp common-lisp

我需要将一个数字列表写入文件,并在行尾添加var obj = {}; obj.name = "dooley" obj.last = "bonheuaa" window.sessionStorage.setItem("me", JSON.stringify( obj));

我尝试过这段代码但只适用于列表的第一个元素。

var me = JSON.parse( window.sessionStorage.getItem("me"))

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

如何将%附加到流中:

(with-open-file (str "filename.txt"
                     :direction :output
                     :if-exists :supersede
                     :if-does-not-exist :create)
  (format str "~A~%" '(1 2 3 4 5)))

在你的情况下,我会做一些事情,比如通过列表并写入流,有点像这样,小心额外的返回,也可以在打开文件之前添加一个控件,如果你不想做如果列表为空,则为任何内容。

(defun write-non-empty-list-to-a-file (file-name lst)
  "writes a non empty list to a file if the list is empty creates the file with a return"
  (with-open-file (str file-name
                     :direction :output
                     :if-exists :supersede
                     :if-does-not-exist :create)
    (dolist (e lst)
      (format str "~A~%" e))
    (format str "~%")));this if you want an extra return

答案 1 :(得分:1)

从描述和代码中,我不能100%确定以下内容是否符合您的要求,但无论如何我都会尝试。此代码段中的代码遍历数值列表并将其写入输出文件:

(defun write-numeric-list(filename l)
  (with-open-file (out filename :direction :output :if-exists :append :if-does-not-exist :create)
    (dolist (segment l)
      (format out "~D " segment))
    (format out "~%")))

示例电话:

(write-numeric-list "output.txt" (list 1 2 -42))

此代码仅为整个列表打开输出文件一次,而不是像原始版本那样为列表中的每个元素打开一次。您可能需要根据特定情况下的前提条件调整:if-exists:if-does-not-exist选项。

事实上,format可以使用稍微高级的格式控制字符串来自己走一个列表。那些控制字符串不是每个人的一杯茶,但作为参考,这里是使用它们的代码版本:

(defun write-numeric-list(filename l)
  (with-open-file (out filename :direction :output :if-exists :append :if-does-not-exist :create)
    (format out "~{~D ~}~%" l)))

答案 2 :(得分:-1)

似乎你想要递归。 我会这样做然后

(defun write-segment (filename segment)
  (labels 
      ((do-write (out segment)
         (cond ((null segment) (format out "~%"))
               (t (format out "~D " (car segment)) 
                  (do-write out (cdr segment))))))
     (with-open-file (out filename
                     :direction :output
                     :if-exists :append
                     :if-does-not-exist :create)
  (do-write out segment))))