Search code examples
vbscriptqtphp-uft

The script is writing a new line beside the first line instead of being last line on a txt


My script has to iterations. On the first one, it reads a txt, takes the firt line and after doing some stuff (creating new string), it writes that string on a temp file and after deleting the original txt, it saves the temp file with the same name as the original txt.

On second iteration, it takes the created txt and tries to write a new line at the end of the file. The problem is that now the code is writing the new line beside the first line, instead of writing it in the last line.

Example:

Expected result: 004;J2Yf;18090023;20200725;00000509990;VOLVO;D;YFWfS9Z9lu06JM0Rk;D;FA;18090023 004;J2Yf;18090023;20200725;00000509990;VOLVO;D;YFWfS9Z9lu06ftR78;D;FA;18090023

Incorrect result: 004;J2Yf;18090023;20200725;00000509990;VOLVO;D;YFWfS9Z9lu06JM0Rk;D;FA;18090023004;J2Yf;18090023;20200725;00000509990;VOLVO;D;YFWfS9Z9lu06ftR78;D;FA;18090023

How can I write on the last line?

TIA ;)

For Iterator 1 to 2
    sF1 = "C:\Users\ig.ext\Desktop\Automation\Archivo.txt"
    '#Opening file  
    Dim objFS 
    Dim objFile
    strTemp = "C:\Users\" & Environment("UserName") & "\Desktop\Automation\Temp.txt"
    Set objFS = CreateObject("Scripting.FileSystemObject")

    If Iterator = 1 Then

        Set objFile = objFS.OpenTextFile(sF1)
        content = objFile.ReadLine

        '#Creating temporal file
        Set objOutFile = objFS.CreateTextFile(strTemp,True)
    Else 
        Set objFile = objFS.OpenTextFile(sF1, 8)        

    End If

    sResultado = "004;J2Yf;18090023;20200725;00000509990;VOLVO;D;YFWfS9Z9lu06ftR78;D;FA;18090023"

    If Iterator = 1 Then

        '#Write and close
        objOutFile.Write(sResultado)

        objOutFile.Close
        objFile.Close
        objFS.DeleteFile(sF1)
        objFS.MoveFile strTemp,sF1
    else

        '#Write line and close
        objFile.Writeline(sResultado)
        objFile.Close
    End If

Next

Solution

  • As @Geert Bellekens commented:

    Use WriteLine() instead of Write() in your first iteration to add a newline before writing the second line.

    (answer added as community wiki)