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

Started by Maurizio, February 18, 2005, 02:52:48 AM

Previous topic - Next topic

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

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

HPW

#1
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.
Hans-Peter

Maurizio

#2
Thank you very much

Maurizio

Sammo

#3
HPW's solution can be reduced to a single line:


(setq inputlist (parse (read-file in-file) "rn"))

eddier

#4
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