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

时间:2015-12-23 09:20:24

标签: emacs elisp

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

(require 'json)
(setq config (json-read-from-string (read-file "config.json")))

4 个答案:

答案 0 :(得分:8)

您可以将代码简化为:

(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)))

答案 1 :(得分:0)

我最终得到了这段代码:

(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))))

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

对于那些不喜欢编写相当多代码的人,可以使用f-read库中的f(不是标准库的一部分)。这来自这个问题:elisp: read file into list of lists