Reading a TXT file using LISP

Here is a simple example of how to read a TXT file into lisp and then do something with the contents. In this example, the TXT file contains coordinates, and the code will draw either points or lines.

One thing to keep in mind. Most times when you open a file for read or write, you should open the file, perform the entire operation, then close the file. Keep the code to a minimum while the file is open. This way if you run into an unhandled error, the file isn’t stuck open, and in the case of shared files, you are not locking the file for an extended amount if time.

Here is a sample of the TXT file we are reading with the code. It contains X and Y values, separated by commas.

3121284.38296466,882181.92380207
3121277.99413417,882267.69275572
3121275.35443066,882375.23306138
3121272.51513517,882482.87407333
3121262.35874024,882580.84966059
3121233.10972356,883133.60346681
3121224.47339393,883240.46739907

Here is the code. Keep in mind that this code was left in a simple form to help show the steps involved. It is not optimized and there is no error checking and/or restoring of changed sysvars. These are topics for a different tutorial.

 

(defun c:foo ( / fn fp lst l)
  ;; Prompt the user to select a .TXT file.
  (setq fn (getfiled "Select ASCII file" "" "txt" 4))

  ;; Prompt the user for what type of entity to draw
  (initget "L P")
  (setq e (getkword "\nWhat type of entity [Line/] "))

  ;; Open the file and create an empty list
  (setq fp (open fn "r") lst '())

  ;; Iterate the file, writing each line to
  ;; the list
  (while (setq l (read-line fp))
    (setq lst (cons l lst))
  )

  ;; Close the file.
  (close fp)

  ;; Reverse the list
  (setq lst (reverse lst))

  ;; At this point, the data is stored in
  ;; a variable and the file is closed.

  ;; Turn off OSMODE
  (setvar "osmode" 0)

  ;; Draw the requested entity type  
  (cond ((eq e "L")
         ;; iterate the list and create lines
	(command "._line")
         (foreach item lst
           (command item)
         )
         (command "")
	)
         ;; --or--
	(t	 
         ;; Set a couple of variables
         (setvar "pdmode" 34)
         (setvar "pdsize" -1.0)

         ;; Iterate the list and draw a point
         ;; entity at each coordinate
         (foreach item lst
           (command "._point" item)
         )
	)
  )

  ;; Close quietly
  (princ)
    
)