Search code examples
file-ioappendmaxscript

Add line to file with MaxScript


I have a file:

A

Some text

Sum up

I can create that file easily with MaxScript's format "..." to:file.

But how to add some lines to already existing and not empty file?

For the most, I would like to add the line with my text:

  1. After specified text occurence (.e.g after Some text, in new line)
  2. At specified line (e.g. in empty line #4 and add new line after it)

If it's not possible, then maybe can I append something to file (write it after Sum up)?


p.s. I could always read the whole file to variable, add my text to it and then save the file.

But it's not really an option for big files (and I want to make it fast).


Solution

  • To append to a file, use the openFile with "a" as the mode argument. The full documentation can be found at FileStream Values:

    fs = openFile "c:/Temp/YourFile.txt" mode:"a"
    print "This line will be appended to your file" to:fs
    close fs
    
    -- Insert some text in the middle of a file
    fsadd = openFile "c:/Temp/YourFile.txt" mode:"a+"
    skipToString fsadd "Some text to write"
    skipToNextLine fsadd
    print "Insert New Text" to:fsadd
    close fsadd