如何在Emacs中以编程方式读取文件内容?

9

我想在.emacs文件中读取config.json文件,应该怎么做?

(require 'json)
(setq config (json-read-from-string (read-file "config.json")))
4个回答

16

您可以将代码简化为:

(defun my-file-contents (filename)
  "Return the contents of FILENAME."
  (with-temp-buffer
    (insert-file-contents filename)
    (buffer-string)))

编辑:虽然在这个特定的例子中,我发现json-read-file已经被定义了,这就省去了中间人。

Emacs 24.5的定义如下:

(defun json-read-file (file)
  "Read the first JSON object contained in FILE and return it."
  (with-temp-buffer
    (insert-file-contents file)
    (goto-char (point-min))
    (json-read)))

3

对于 JSON 文件,只需使用 json-read-file。对于其他文件,f 库提供了 f-read-bytesf-read-text

(f-read-text "file.txt" 'utf-8)

1
我最终得到了这段代码:

(defun read-file (filename)
  (save-excursion
    (let ((new (get-buffer-create filename)) (current (current-buffer)))
      (switch-to-buffer new)
      (insert-file-contents filename)
      (mark-whole-buffer)
      (let ((contents (buffer-substring (mark) (point))))
        (kill-buffer new)
        (switch-to-buffer current)
        contents))))

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接