How Can I Add a Line to the Top of a Text File?

How Can I Add a Line to the Top of a Text File?

  • Comments 4
  • Likes
Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I add a line to the top of a text file?

-- FT

SpacerHey, Scripting Guy! AnswerScript Center

Hey, FT. You know, at one point in his career Sir Arthur Conan Doyle actually killed off Sherlock Holmes, figuring he’d written everything anyone could ever write about the master detective. Public outcry soon made him change his mind, and in short order he brought Sherlock Holmes back to life. (Creating, along the way, the basic plotline for every soap opera ever written.)

We Scripting Guys can empathize with Sir Arthur Conan Doyle. After all, we periodically think, “Well, that’s it; we’ve finally written everything anyone could ever write about text files.” No sooner do we think that than we seem to get a flurry of questions about text files, including three people who asked this same thing: how can I add a line to the top of a text file?

Elementary, my dear Watson (uh, my dear FT). All you have to do is use a script similar to this:

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Scripts\Test.txt", ForReading)

strContents = objFile.ReadAll
objFile.Close

strFirstLine = "This is the new first line in the text file."
strNewContents = strFirstLine & vbCrLf & strContents

Set objFile = objFSO.OpenTextFile("C:\Scripts\Test.txt", ForWriting)
objFile.WriteLine strNewContents

objFile.Close

Note. Interestingly enough, in the original stories Sherlock Homes never said, “Elementary, my dear Watson.” No, we don’t know why he didn’t say it; he just didn’t.

Ah, yes, now the game is afoot, isn’t it? We begin by creating a pair of constants - ForReading and ForWriting - that we’ll use when working with our text file. We create an instance of the FileSystemObject and then use the OpenTextFile method to open the file C:\Scripts\Test.txt for reading:

Set objFile = objFSO.OpenTextFile("C:\Scripts\Test.txt", ForReading)

Now that the file is open we use the ReadAll method to read the entire contents of the file and store those contents in a variable named strContents. We then immediately close the file Test.txt. Why? Well, the FileSystemObject allows you to open a file for reading or for writing, but you can’t do both at the same time. To add a new line to the top of the file, we’re going to have to write to the file; that means we’ll have to reopen it, but for writing.

Next we need to construct the new contents for the file. We can’t directly add a line to the top of the text file; the FileSystemObject only allows you to add new lines to the end of a text file. Therefore, what we’ll have to do is create an entirely new file in memory and then replace the existing contents of Test.txt with this new file. Our new file will consist of three parts: a new first line; a carriage return-linefeed; and the existing contents of the file. To construct this file we start off by using this code to store the new first line in a variable named strFirstLine:

strFirstLine = "This is the new first line in the text file."

We then use this line of code to concatenate the new first line, a carriage return-linefeed (using the VBScript constant vbCrLf) and the existing contents of the file (which we stored in the variable strContents):

strNewContents = strFirstLine & vbCrLf & strContents

All that’s left now is to reopen Test.txt (for writing this time), then use the WriteLine method to replace the exiting contents with our new file:

Set objFile = objFSO.OpenTextFile("C:\Scripts\Test.txt", ForWriting)
objFile.WriteLine strNewContents

We then call the Close method and, just like that, case closed. Well, OK, file closed. Hey, we’re just trying to do what Sherlock Holmes would do.

Speaking of which, did you know that Sherlock Holmes had an older brother named Mycroft? It’s true. Supposedly Mycroft had a lot of potential, but was too lazy to really do anything interesting or useful.

Hey, what do you mean that sounds familiar? Never mind; you’re probably thinking about some other daily scripting columnist.

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Nice!  It solved one problem for me and created another, but only when I loop back and use it again.  I get a Name redefined error for the ForReading constant (I thought a constant did not get redefined??!).  I tried to give the second and third use (I am concatenating three files _and_ adding a line on top) different names, but I still get the error the second time around.

    Any ideas why?  Should I never use this stretch of code twice?

  • @peltier_cooler

    No one can possibly know what you are talking about.  We have no idea what code you are running.  It is not the code above.

    #2 - this blog post is almost 10 years old.  Did you realize that.

    If you need scripting help use the 'Scripting Forum" link to your right on this page.  Post your code and question and a link to this blog.

  • jrv,

    I certainly do know it's from 2005 (I don't just copy code, I sometimes read it and the comments).  I was asking in a general way, as I do seriously lack background in WSH...and I like to solve my own problems.

    Still, I may ask in the fora if I don't figure it out fairly soon.  Thanks for the assistance.

  • In the end I replaced

    Const ForReading = 1

    with

    Dim ForReading

    ForReading = 1

    and kept everything else more or less the same.  It has worked a dozen times on two machines today in constant use, so my question still remains, but at least I have a workaround.