Lesson 6 of 18

Fixing the Empty Line - Appending To Variables

Duration: 2:45 Watch on YouTube (external link, opens in new tab)

Markdown version

In this lesson

To remove the empty line, Roy Osherove appends the content of each file, with a new line, to a variable named with a v prefix, and replaces the placeholder with that variable once, after the loop. He notes that the script runs a bit slowly, partly because of the virtual machine it runs on and, he guesses, because FinalBuilder (external link, opens in new tab) also saves the variables to files, but that it is fast enough for the purpose.

Transcript

386 words

[00:01] (external link, opens in new tab) Let's solve the problem from the previous video where we have this empty line. Maybe we're going about this the wrong way. Maybe instead of just appending for each file, maybe we should just accumulate all this text into a new variable and then just replace whatever we had in this line with a new variable and that will be it. So let's see if we how we can actually do that. First let's create a new variable here. We'll call that let's call it v. So that we'll know from this moment on our variables will have these naming conventions.

[00:35] (external link, opens in new tab) So v slash all inputs and what we're going to do is that for after we read the text while we put stuff inside important contents we're going to look for the word append here and append to a variable the value of important content. So the variable that we have is v all inputs.

[01:06] (external link, opens in new tab) Let's append to it important contents from that file. We can add a CRLF so a new line every time we append something. So by the end of the iteration we can just have V all inputs and we can just replace things here. So now maybe we don't need to write to the text file here. Let's delete this line here. And let's move the replacement thing here just under the loop after it.

[01:39] (external link, opens in new tab) And I'm going to replace put stuff here from the file with v all inputs which should contain by the end of this loop iteration the value of all the stuff combined. So, let's save that and run it and see what happens. Running, running, running, running, running. And now we should be able to see what happens.

[02:09] (external link, opens in new tab) Let's see. New filet txt. Now there is no empty line. We still have all that value. So, another way to work with variables is to hold them and append to them in memory and then use all that stuff. Notice that it's running a bit slow. Part of it is because it's running on a virtual machine on a Mac. On part of it is because the way that FinalBuilder works, it also saves the variables locally to files, I guess. So, it takes a bit more time, but for our purposes, it's definitely fast enough.