首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何更改Common ` file‘的用法,以便将元素追加到文件中的列表中?

如何更改Common ` file‘的用法,以便将元素追加到文件中的列表中?
EN

Stack Overflow用户
提问于 2021-08-13 22:51:36
回答 1查看 81关注 0票数 0

我正在使用Common (SBCL)。目前,我可以编写一个文件附加列表。为了举例说明,让我们首先定义一些变量,以便更容易理解:

代码语言:javascript
复制
(defvar example-1 '((d-1 u-1) (i-1) (i-2)))
(defvar example-2 '((d-2 u-2) (i-1) (i-2)))

现在,在REPL中:

代码语言:javascript
复制
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”,我可以看到:

代码语言:javascript
复制
 ((D-1 U-1) (I-1) (I-2)) 
 ((D-2 U-2) (I-1) (I-2)) 

好的。这是,接近我想要的,

然而,我希望把所有的东西都包装在一个清单中:

代码语言:javascript
复制
(

 ((D-1 U-1) (I-1) (I-2)) 
 ((D-2 U-2) (I-1) (I-2)) 

)

因此,每当某个东西被“附加”到文件中时,它就应该在这个列表中。我正在改变这一点,因为它将使这个文件更容易阅读和工作。我需要过滤添加的元素。

为了得到这个输出,我需要在with-open-file函数中修改什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-13 22:58:28

使用对WITH-OPEN-FILE的单个调用,并将所有内容合并到一个列表中。

代码语言:javascript
复制
(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))

如果每次写入时都要追加到列表中,则需要读取列表,追加到列表中,然后用更新的列表覆盖文件。

代码语言:javascript
复制
(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)))
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68779052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档