我正在使用Common (SBCL)。目前,我可以编写一个文件附加列表。为了举例说明,让我们首先定义一些变量,以便更容易理解:
(defvar example-1 '((d-1 u-1) (i-1) (i-2)))
(defvar example-2 '((d-2 u-2) (i-1) (i-2)))现在,在REPL中:
CL-USER> (with-open-file (str "/home/pedro/miscellaneous/misc/tests-output/stack-overflow.lisp"
:direction :output
:if-exists :append
:if-does-not-exist :create)
(format str " ~S ~%" example-1))
CL-USER> (with-open-file (str "/home/pedro/miscellaneous/misc/tests-output/stack-overflow.lisp"
:direction :output
:if-exists :append
:if-does-not-exist :create)
(format str " ~S ~%" example-2))如果我去签出文件“堆栈-溢出. file”,我可以看到:
((D-1 U-1) (I-1) (I-2))
((D-2 U-2) (I-1) (I-2)) 好的。这是,接近我想要的,。
然而,我希望把所有的东西都包装在一个清单中:
(
((D-1 U-1) (I-1) (I-2))
((D-2 U-2) (I-1) (I-2))
)因此,每当某个东西被“附加”到文件中时,它就应该在这个列表中。我正在改变这一点,因为它将使这个文件更容易阅读和工作。我需要过滤添加的元素。
为了得到这个输出,我需要在with-open-file函数中修改什么?
发布于 2021-08-13 22:58:28
使用对WITH-OPEN-FILE的单个调用,并将所有内容合并到一个列表中。
(with-open-file (str "/home/pedro/miscellaneous/misc/tests-output/stack-overflow.lisp"
:direction :output
:if-exists :overwrite
:if-does-not-exist :create)
(pprint (list example-1 example-2) str))如果每次写入时都要追加到列表中,则需要读取列表,追加到列表中,然后用更新的列表覆盖文件。
(defun append-to-list-in-file (filename new-item &aux contents) ;;;;
(setq contents (list)) ;; default in case reading fails
(ignore-errors
(with-open-file (str filename :direction :input)
(setq contents (read str))))
(setq contents (nconc contents (list new-item)))
(with-open-file (str filename :direction :output :if-exists :overwrite)
(write contents :stream str)))https://stackoverflow.com/questions/68779052
复制相似问题