How do I read a text file line by line &put it into a li

For the Compleat Fan
Locked
HJH
Posts: 21
Joined: Tue May 31, 2005 2:21 pm
Location: Europe

How do I read a text file line by line &put it into a li

Post by HJH »

Hi

as a relative newcomer to Lisp and especially newLisp I would like to ask how a function in good style looks like which does the following:

It reads in a text file line by line and gives back a list of all this lines.

Call

Code: Select all

(read-textfile-into-list "myFile.txt")
There is a partial answer in the documentation
http://www.newlisp.org/downloads/manual_frame.html
command open

and there is a read-line function. However I do not know how to properly properly initialize the list? Which functions should I use to append to the list?

Regards
HJH

Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

Hello HJH,

(setq list-of-lines (parse (read-file "myfile.txt") "\r\n"))

will do the job in which 'read-file' reads the entire file as a big ol' string, 'parse' with "\r\n" separates the string into a list of lines (use "\n" instead of "\r\n" if not Windows), and 'setq' associates the resulting list with the symbol 'list-of-lines'.

HJH
Posts: 21
Joined: Tue May 31, 2005 2:21 pm
Location: Europe

Post by HJH »

Sammo wrote: (setq list-of-lines (parse (read-file "myfile.txt") "\r\n"))
Thank you Sammo. This is very compact and readable at the same time.
It works fine and what is exciting: It reads UTF8 characters right out of the box (well, I had to install the exe).

For the number of files I am dealing with this solution is fine (100...400 files, 5kB each) but if somebody has a more conventional solution with read-line I am curious to know it as well.

HJH

Sammo
Posts: 180
Joined: Sat Dec 06, 2003 6:11 pm
Location: Loveland, Colorado USA

Post by Sammo »

Code: Select all

(setq list-of-lines '())
(setq myfile (open "myfile.txt" "read"))
(while (read-line myfile)
    (push (current-line) list-of-lines -1))
(close myfile)

Locked