MacOS – AppleScript: How to write to a specific line of a text file

applescriptmacostext;

Sample contents of a .txt file on my Mac:

This is sentence A.
This is sentence B.
This is sentence C.
This is sentence D.
This is sentence E.

I want to implement a subroutine, like this:

writeTextAtSpecificLine(("This is the newcomer sentence." & linefeed), 4)

so that, the text file would consequently look like this:

This is sentence A.
This is sentence B.
This is sentence C.
This is the newcomer sentence
This is sentence D.
This is sentence E.

I know that I can accomplish my desired result by making each line of the text file its own item in an AppleScript list object, like so:

set theIndividualLinesOfTextFileAsList to paragraphs of (read theFilepathOfTxtFile)

I could then split the list, based on the desired line number, and then add it all back together.

But, does a more efficient method exist?

My real .txt file is much longer than the sample content above.

Best Answer

Edited version:

set selected_file to ((path to documents folder as text) & "hom.txt") as alias
set text_data to "This is the newcomer sentence."

InsertLine(selected_file, text_data, 4)

on InsertLine(the_file, the_data, num_line)
    try
        set file_id to open for access the_file with write permission
        set text_data to read file_id

        -- CHECK EMPTY LINE
        if (paragraph num_line of text_data) ≠ "" then
            set the_offset to (offset of (paragraph num_line of text_data) in text_data) - 1
            set remaining_data to (the_data) & (text the_offset thru -1) of text_data
            set eof of file_id to the_offset
        else -- LINE IS EMPTY
            set num_line to num_line - 1
            set the_count to (count of (characters of (paragraph num_line of text_data))) - 1
            set the_offset to (offset of (paragraph num_line of text_data) in text_data) + the_count + 2
            set remaining_data to the_data & linefeed & ((text (the_offset + 1) thru -1) of text_data)
            set eof of file_id to the_offset - 1
        end if

        -- WRITE DATA TO FILE
        --write the_data to file_id -- INSERT LINE
        write remaining_data to file_id -- WRITE REMAINING DATA
        close access file_id
    on error
        try
            close access the_file
        end try
    end try
end InsertLine