Page 1 of 1

Is it there a better way to read a file in a list ?

Posted: Fri Feb 18, 2005 10:52 am
by Maurizio
I'd like to read a file in a list, having each line as a separate string.
I've tried this, but it seems to me a little clumsy.
Is it there a better way ?
Regards
Maurizio

Code: Select all

(define (read-my-file)
  (set 'lst '())
  (set 'in-file (open "myfile.txt" "read"))
  (while (read-line in-file) 
    (set 'lst (append lst (list (current-line)))))
  (close in-file)
  lst)

Posted: Fri Feb 18, 2005 12:45 pm
by HPW
I used this:

(setq inputstring (read-file in-file))
(setq inputlist (parse inputstring "\r\n"))
(dolist(linestr inputlist)
...)

The parse pattern may vary from platform from "\r\n" to "\n".

Depends on if you need the whole file in a list or if you can
process each line seperatly. Reading whole file give speed
but cost memory.

Posted: Fri Feb 18, 2005 1:35 pm
by Maurizio
Thank you very much
Maurizio

Posted: Fri Feb 18, 2005 2:42 pm
by Sammo
HPW's solution can be reduced to a single line:

Code: Select all

(setq inputlist (parse (read-file in-file) "\r\n"))

Posted: Fri Feb 18, 2005 5:24 pm
by eddier
I'm always having to work with reports. A nice thing about newLISP is the fact I can read and parse a tab delimited file exported from Excel, Access, whatever in a one liner:

Code: Select all

(setq data (map (fn (x) (parse x "\t")) (replace "\r" (parse (read-file in-file) "\n"))))
Note that with (replace "\r" (parse ... I don't have to worry if the file came from UNIX/LINUX :) or Windoze :(

Eddie