how to write to a file in emacs
Asked Answered
R

3

12

I want the emacs lisp code to append some data to a log file from emacs. The log file is large so I don't want to read it into memory.

I just need to open the log file, append some data to it, close it. I never need to see or manually edit the content.

Recurrent answered 26/3, 2011 at 14:48 Comment(2)
Do you need to use emacs to perform this? Couldn't you just use the redirect function (>>) to append the new data?Jeseniajesh
no I want to write an write-file-hook so that every time I write a file i append an entry to the log fileRecurrent
M
14

You can use the append-to-file lisp function.

Append the contents of the region to the end of file filename. When called from a function, expects three arguments, start, end and filename. start and end are normally buffer positions specifying the part of the buffer to write.

If start is nil, that means to use the entire buffer contents.

If start is a string, then output that string to the file instead of any buffer contents; end is ignored.

More information is available here

Maher answered 26/3, 2011 at 15:0 Comment(2)
I came across this two years after the fact and it was one of those "the thing you needed, emacs provided for you all along!" moments. Thank you.Unwonted
I wanted to overwrite a file rather than append to the file. For this you can use (write-region "file-contents" nil "/tmp/file"). This incidentally also takes an append argument.Crump
L
7
(defun add-log-entry (log-message log-file)
  "Add a given message string to the end of a file."
  (append-to-file log-message nil log-file))
Lagunas answered 28/3, 2011 at 11:18 Comment(0)
G
0
(f-write (format "%s" \<your list or what you what> ) 'utf-8\<or other encoding> "\<absolute file path>")

then go to the end of this line on closing braket and press C-e , go to the terminal cat + file, enjoy

Gelatinate answered 30/5, 2022 at 0:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.