newLISP Fan Club

Forum => Anything else we might add? => Topic started by: Maurizio on February 18, 2005, 02:52:48 AM

Title: Is it there a better way to read a file in a list ?
Post by: Maurizio on February 18, 2005, 02:52:48 AM
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

(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)
Title:
Post by: HPW on February 18, 2005, 04:45:28 AM
I used this:



(setq inputstring (read-file in-file))

(setq inputlist (parse inputstring "rn"))

(dolist(linestr inputlist)

  ...)



The parse pattern may vary from platform from "rn" 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.
Title:
Post by: Maurizio on February 18, 2005, 05:35:46 AM
Thank you very much

Maurizio
Title:
Post by: Sammo on February 18, 2005, 06:42:12 AM
HPW's solution can be reduced to a single line:


(setq inputlist (parse (read-file in-file) "rn"))
Title:
Post by: eddier on February 18, 2005, 09:24:30 AM
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:



(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