Author Topic: edit text file from lisp question  (Read 5889 times)

0 Members and 1 Guest are viewing this topic.

alanjt

  • Needs a day job
  • Posts: 5352
  • Standby for witty remark...
edit text file from lisp question
« on: March 28, 2008, 09:08:58 AM »
is it possible to edit a file (text) from lisp?
i want to find the file, delete everything on a specific line and replace with a new string of text. is this possible?
Civil 3D 2019 ~ Windohz 7 64bit
Dropbox

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16899
  • Superior Stupidity at its best
Re: edit text file from lisp question
« Reply #1 on: March 28, 2008, 09:22:29 AM »
Yep

I don't have time to write any code, but I can give you some general directions. There may be multiple methods and this is merely one.

Open the file using "open", loop through each line, saving it to a local variable, until you find the line you want using "read-line", as soon as you find the target line, add your line to replace to your list of lines, then finish reading the file using "read-line" saving the line data to your local variable, close the file using "close" and immediately reopen that file in write mode, then write all your saved variables to that file and close the file.
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

CAB

  • Global Moderator
  • Seagull
  • Posts: 10401
Re: edit text file from lisp question
« Reply #2 on: March 28, 2008, 09:28:53 AM »
Do a search on readfile
Here is an example subroutine.
Code: [Select]
  ;;  TxtFile2List by CAB
  ;;  open the file, read the data
  ;;  returns data from file
  (defun File2list (filename ; file name
                    onestr ; t = all lines 2 one string
                    case ; nil = no change
                    ;;         U = force to upper case
                    ;;         L = force to lower case
                    / handle stream itm FileData
                   )
    (if
      (and
        (eq 'str (type filename))
        (setq filename (findfile filename))
        (setq handle (open filename "r"))
      )
       (progn
         (while (setq stream (read-line handle))
                  (setq  FileData (cons stream FileData))
         ) ; while
         (close handle)
         
         (if FileData
           (setq FileData
                   (mapcar '(lambda(itm) 
                        (cond
                          ((= case "U") (setq itm (strcase itm)))
                          ((= case "L") (setq itm (strcase itm t)))
                        ) ; cond stmt
                        (if (/= (vl-string-trim " \t\n" itm) "")
                          (if onestr
                            (setq itm (strcat itm (chr 13) itm))
                            (setq itm (cons itm result))
                          )
                        )
                     )
                  (reverse FileData)
                  )
       )
       ) ; progn
    ) ; endif
     FileData
  )

Here is a write example:
Code: [Select]
(defun c:tabs->prn (/ fn itm)
  (if (setq fn (open "Tab Names.txt" "w"))
    (progn
      (foreach itm (layoutlist)
        (write-line itm fn)
      )
      (close fn)
    )
    (prompt "\nFile 'Tab Names.txt' created.")
  )
  (princ)
)
I've reached the age where the happy hour is a nap. (°¿°)
Windows 10 core i7 4790k 4Ghz 32GB GTX 970
Please support this web site.

CAB

  • Global Moderator
  • Seagull
  • Posts: 10401
Re: edit text file from lisp question
« Reply #3 on: March 28, 2008, 09:36:19 AM »
More stuff you'll need to look into.


(getfiled title default ext flags)
Prompts the user for a file name with the standard AutoCAD file dialog box, and returns that file name

vl-filename-base
(vl-filename-base "c:\\acadwin\\acad.exe")
"ACAD"

vl-filename-directory
(vl-filename-directory "c:\\acadwin\\acad.exe")
"C:\\ACADWIN"

vl-filename-extension
    (vl-filename-extension "c:\\acadwin\\acad.exe")
    ".EXE"
I've reached the age where the happy hour is a nap. (°¿°)
Windows 10 core i7 4790k 4Ghz 32GB GTX 970
Please support this web site.

septicad

  • Guest
Re: edit text file from lisp question
« Reply #4 on: March 28, 2008, 10:15:38 AM »
Here is my version:  i wrote this using info i obtained from

http://www.jefferypsanders.com/autolisptut.html
http://www.afralisp.net

I use this method to edit a list of notes stored in a text file.  Everything is DCL driven... so different buttons calls functions that manipulate the list (delete, edit, swap, add new notes).  A secondary function lets the user select multiple items in a list box and places notes in an itemized list in an mText entity...


Code: [Select]
(defun c:tst ()

  ;;;--- Set up an empty list
  (setq labelList(list))

  ;;;--- Open the text file
  (if (findfile "c:\\file.txt")
    (progn
      (if (setq fil(open (findfile "c:\\file.txt") "r"))
        (progn
          ;;;--- Read the lines of data in the text file
          (while (setq a (read-line fil))
            ;;;--- Add the data to the list
            (setq labelList
              (append
                labelList
                (list a)
              )
            )
          )
          ;;;--- Close the file.
          (close fil)
        )
      )
    )
  )

  ;;;--- REQUIRED??? - I needed to add this to put the list into a DCL list
  ;;;--- I think it removes the end of line markers???? - not sure if this is alway required.
   (setq formList(list))
   (foreach a labelList
     (setq formList(append formList(list a)))
   )

;;;; NOW do what you want with each line of text stored in the variable formList
;;;; Change order of list, delete lines, edit lines... etc...
;;;; the code i wrote is too disorderly to present here...
;;;; NOW do what you want with the list using a loop


;;;--- write changes back to file
        (setq f (open "c:\\file.txt" "w"))

; loop to write list to file
(foreach item formlist
  (write-line item f)
)

        ;;;--- Close the file.
        (close f)

)
; end function

alanjt

  • Needs a day job
  • Posts: 5352
  • Standby for witty remark...
Re: edit text file from lisp question
« Reply #5 on: March 28, 2008, 12:32:35 PM »
ok, this is what i have so far...how do i get it to choose a specific line and overwrite that?

Code: [Select]
(defun c:test (/ fn itm)
  (if
(setq fn (open "c:\\sdsk-test.dfm" "w"))


;the line i want to replace is on 124


;this will replace fn when i get it to write to the correct line;(setq fn (open (strcat "C:\\Documents and Settings\\" (getvar "loginname") "\\Local Settings\\Application Data\\Autodesk\\AutoCAD Civil 3D Land Desktop Companion 2008\\R17.1\\enu\\Support\\sdsk.dfm" "w")))

    (progn
        (setq itm "PROT=(G:\cadd standards\Surveying\Prototypes\,Project Prototypes)")
        (write-line itm fn)
      (close fn)
    )
  )
  (princ)
)
Civil 3D 2019 ~ Windohz 7 64bit
Dropbox

septicad

  • Guest
Re: edit text file from lisp question
« Reply #6 on: March 28, 2008, 01:05:32 PM »
try this....

Code: [Select]
(defun c:tst (/ $TEXT $FILENAME lineList newList LineNumToChange)

  (setq LineNumToChange 1)

; set filename to change
  (setq $FILENAME "c:/temp.txt")

; new text to swap out with old
  (setq $TEXT "fasdasdjkflflasdjkasdjklsdflasdfla")

;;;--- Open the text file
  (if (findfile $FILENAME)
    (progn
      (if (setq fil(open (findfile $FILENAME) "r"))
        (progn
          ;;;--- Read the lines of data in the text file
          (while (setq a (read-line fil))
            ;;;--- Add the data to the list
            (setq lineList
              (append
                lineList
                (list a)
              )
            )
          )
          ;;;--- Close the file.
          (close fil)
        )
      )
    )
  )

 
  (setq count 0)
  (foreach item lineList
    (progn 
     (if (= count (- LineNumToChange 1))
      (setq newList(append newList(list $TEXT))); if true do this
      (setq newList(append newList(list item))); if false do this
     )
     (setq count (+ count 1))
    )
  )


;;;--- write changes back to file
  (setq f (open $FILENAME "w"))

; loop to write list to file
  (foreach item newlist
   (write-line item f)
  )

;;;--- Close the file.
  (close f)

)

alanjt

  • Needs a day job
  • Posts: 5352
  • Standby for witty remark...
Re: edit text file from lisp question
« Reply #7 on: March 28, 2008, 02:48:39 PM »
oh man, thank you soooooo much. i had no intentions of anyone doing all the work for me, i just didn't have any idea where to go from with something like this.

thank you guys so much.
Civil 3D 2019 ~ Windohz 7 64bit
Dropbox

alanjt

  • Needs a day job
  • Posts: 5352
  • Standby for witty remark...
Re: edit text file from lisp question
« Reply #8 on: March 28, 2008, 03:27:43 PM »
here is the actual version in case anyone wants this. i knew their had to be a better way to customizing the sdsk.dfm than having just one that everyone on the network looks to.

thank you thank you thank you

Code: [Select]
(defun c:test (/ $TEXT $FILENAME lineList newList LineNumToChange)

  (setq LineNumToChange 124)

; set filename to change
   (setq $FILENAME (findfile "SDSK.DFM"))

; new text to swap out with old
  (setq $TEXT "PROT=(G:\\cadd standards\\Surveying\\Prototypes\\,Project Prototypes)")

;;;--- Open the text file
  (if (findfile $FILENAME)
    (progn
      (if (setq fil(open (findfile $FILENAME) "r"))
        (progn
          ;;;--- Read the lines of data in the text file
          (while (setq a (read-line fil))
            ;;;--- Add the data to the list
            (setq lineList
              (append
                lineList
                (list a)
              )
            )
          )
          ;;;--- Close the file.
          (close fil)
        )
      )
    )
  )

 
  (setq count 0)
  (foreach item lineList
    (progn 
     (if (= count (- LineNumToChange 1))
      (setq newList(append newList(list $TEXT))); if true do this
      (setq newList(append newList(list item))); if false do this
     )
     (setq count (+ count 1))
    )
  )


;;;--- write changes back to file
  (setq f (open $FILENAME "w"))

; loop to write list to file
  (foreach item newlist
   (write-line item f)
  )

;;;--- Close the file.
  (close f)
(princ)
)
« Last Edit: March 28, 2008, 03:42:34 PM by alanjt »
Civil 3D 2019 ~ Windohz 7 64bit
Dropbox

septicad

  • Guest
Re: edit text file from lisp question
« Reply #9 on: March 28, 2008, 04:09:09 PM »
no problem.  this is a relatively novice question...so i figure "the simplton" should answer it...  I've gotten plenty of help through forums so...help when you can.

efernal

  • Bull Frog
  • Posts: 206
Re: edit text file from lisp question
« Reply #10 on: March 28, 2008, 04:35:13 PM »
Code: [Select]
;; here another

;; *************************************************************
;; Wrote by Eduardo Fernal
;; 28/03/2008
;; http://www.gr-acad.com.br
;; *************************************************************
(DEFUN c:changelist (/        dh       w@       msg      flag
                     file     line     temp     lista    new_list
                     numero_linha
                     ;; local functions vars
                     exec     replace  sel_list
                    )
  ;; local functions
  (DEFUN exec (/ temp)
    (IF (AND (= flag 1) (> (LENGTH lista) 0))
      (PROGN (SETQ temp (OPEN file "w"))
             (FOREACH x lista (WRITE-LINE x temp))
             (CLOSE temp)
             (STARTAPP "NOTEPAD.EXE" file)
      )
      nil
    )
  )
  ;; end of EXEC function
  (DEFUN sel_list (n)
    (SETQ numero_linha (ATOI n)
          string       (NTH numero_linha lista)
    )
    (SET_TILE "txt" string)
    (SET_TILE "string" "")
  )
  ;; end of SEL_LIST
  (DEFUN replace (/ cn new old line item)
    (IF (AND numero_linha
             (>= numero_linha 0)
             (< numero_linha (LENGTH lista))
             (SETQ new (GET_TILE "string"))
             (SETQ old (GET_TILE "txt"))
        )
      (PROGN (SETQ cn 0
                   new_list '()
             )
             (REPEAT (LENGTH lista)
               (IF (= cn numero_linha)
                 (SETQ new_list (APPEND new_list (LIST (SETQ item new))))
                 (SETQ new_list (APPEND new_list
                                        (LIST (SETQ item (NTH cn lista)))
                                )
                 )
               )
               (SETQ cn (1+ cn))
             )
             ;;
             (START_LIST "lista" 1 numero_linha)
             (ADD_LIST new)
             (END_LIST)
             ;;
             (SETQ lista new_list)
             (SETQ numero_linha nil)
             (SET_TILE "txt" "")
             (SET_TILE "string" "")
             (SETQ flag 1)
      )
      (ALERT
        "Error:\n\n\tPlease, select a line before pressing UpDate button\t\n\n"
      )
    )
  )
  ;; end of replace function
  ;;
  ;; end of local functions
  (IF (SETQ file (GETFILED "Select a txt file" "c:\\" "txt" 8))
    (PROGN
      ;; Writting the dcl file...
      (IF (NOT (FINDFILE "efernal_changelist.dcl"))
        (PROGN
          (SETQ temp (OPEN "efernal_changelist.dcl" "w"))
          (FOREACH x
                   '("ch:dialog{label=\"E.Fernal Software\";key=\"efernal\";fixed_width=true;"
                     ":column{alignment=centered;"
                     ":list_box{tabs=\"8 16 24 32 40 48\";label=\"Txt file contents\";key=\"lista\";width=120;height=16;fixed_width=true;fixed_height=true;}"
                     ":text{label=\"Selected text:\";}"
                     ":text{alignment=centered;width=90;fixed_width=true;label=\"__________________________________________________________________________________________\";}"
                     ":text{label=\"\";key=\"txt\";width=90;alignment=centered;}"
                     ":text{alignment=centered;width=90;fixed_width=true;label=\"__________________________________________________________________________________________\";}"
                     ":text{label=\"Type new text bellow, then press Update button:\";}"
                     ":edit_box{key=\"string\";width=120;fixed_width=true;edit_limit=251;}"
                     ":row{alignment=centered;fixed_width=true;height=3;fixed_height=true;"
                     ":button{label=\"&Help\";key=\"help\";width=12;height=2;fixed_width=true;fixed_height=true;alignment=top;}"
                     ":button{label=\"&Cancel\";key=\"cancel\";is_cancel=true;width=12;height=2;fixed_width=true;"
                     "fixed_height=true;alignment=top;}"
                     ":button{label=\"Accept\";key=\"accept\";is_default=true;width=12;height=2;"
                     "fixed_width=true;fixed_height=true;alignment=top;}"
                     ":button{label=\"&Update\";key=\"replace\";width=12;height=2;fixed_width=true;"
                     "fixed_height=true;alignment=top;}}}}"
                    )
            (PRINC x temp)
          )
          (CLOSE temp)
          (SETQ temp nil)
        )
      )
      ;; Dcl file now exists...
      ;; Reading the txt file to change...
      (SETQ temp (OPEN file "r"))
      (WHILE (SETQ line (READ-LINE temp))
        (SETQ lista (APPEND lista (LIST line)))
      )
      (CLOSE temp)
      (IF (> (SETQ dh (LOAD_DIALOG "efernal_changelist.dcl")) 0)
        (IF (NEW_DIALOG "ch" dh)
          (PROGN (SETQ flag nil
                       msg  "Please, write your help message here..."
                 )
                 (START_LIST "lista")
                 (MAPCAR 'ADD_LIST lista)
                 (END_LIST)
                 ;;
                 (ACTION_TILE "lista" "(sel_list $value)")
                 (ACTION_TILE "help" "(ALERT msg)")
                 (ACTION_TILE "replace" "(replace)")
                 (ACTION_TILE "cancel" "(DONE_DIALOG 0)")
                 (ACTION_TILE "accept" "(DONE_DIALOG 1)")
                 (SETQ w@ (START_DIALOG))
                 (UNLOAD_DIALOG dh)
                 (COND ((= w@ 0) (PRINC "\n-> Cancelled..."))
                       ((= w@ 1) (exec))
                 )
          )
          nil
        )
        (ALERT "Error:\n\n\tUnable to write/load dcl file...\t\n\n")
      )
    )
    (ALERT "Error:\n\n\tTxt file not selected...\t\n\n")
  )
  (PRINC)
)
(PRINC "\n-> Type CHANGELIST and press enter to run...")
(PRINC "\n-> http://www.gr-acad.com.br")
(PRINC)
e.fernal

CAB

  • Global Moderator
  • Seagull
  • Posts: 10401
Re: edit text file from lisp question
« Reply #11 on: March 28, 2008, 05:36:25 PM »
This is how I would do it using sub functions.
Note thst the line number is base zero.
Code: [Select]
(defun c:test (/ $TEXT $FileName FullFileName DataList err
               LineNumToChange)

  ;;  Returns a list of file contents or nil
  (defun file2list (fln / lst ltext fn)
    (if (setq fn (open fln "r"))
      (progn
        (while (setq ltext (read-line fn))
          (setq lst (cons ltext lst)))
        (close fn)
      )
    )
    (reverse lst) ; return the list
  )

  ;;  OverWrite a file with a list of strings
  ;;  returns nil if sucessful else an error message
  (defun list2file (fln lst / fn err)
    (cond
      ((not (setq fn (open fln "w")))
       "Open Failed")
       ((not (mapcar '(lambda(x)(write-line x fn)) lst))
        "Opened, but write failed")
       ((setq err (close fn)))
     )
  )

(defun replacenth (n item lst) ;;D. C. Broad, Jr.
  (if lst
    (if (zerop n)
      (cons item (cdr lst))
      (cons (car lst)(replacenth (1- n) item (cdr lst))))))

  ;;  <<<<<<<<<<<<<<<<<<<
  ;;      Start Here     
  ;;  <<<<<<<<<<<<<<<<<<<
 
  (setq LineNumToChange 124) ; base 0, so the first line is zero
  (setq $FILENAME "SDSK.DFM")) ; SOURCE FILE
 
  ;; new text to swap out with old
  (setq $TEXT "PROT=(G:\\cadd standards\\Surveying\\Prototypes\\,Project Prototypes)")

  ;;  Open & Read File, attempt to get data
  (cond
    ((null (setq FullFileName (findfile $FileName)))
     (princ "\nFile not found.")
    )
    ((null (setq DataList (file2list FullFileName)))
     (PRINC "\nNo data found in file.")
    )
    ((< (length Datalist) LineNumToChange)
     (princ "\nNot enough lines in file.")
    )
    (T ; if you are here all is ok
     (setq DataList (replacenth LineNumToChange $TEXT DataList))
     (if (setq err (list2file FullFileName DataList))
       (princ (strcat "\n" err))
     )
    )
  )
(princ)
)
I've reached the age where the happy hour is a nap. (°¿°)
Windows 10 core i7 4790k 4Ghz 32GB GTX 970
Please support this web site.