All Tutorials / JustinRatliff / Reading and Writing with Files

Reading and Writing with Files

Step 5. Make a temp folder, file and read a file

To work with text files, you'll probably want a folder or primary location where you are going to store files that you read and write. In this example we want to create a folder on the c:/ drive named "temp".

Let me show you why, if you Click Start on the "ReadFile" script (without the "c:/temp" folder and a text file to read, you will get an error message stating "File does not exist".
User-inserted image

Lets look at the code of this script to see how our file is called up to read it. Click on the gear icon (settings) for the "ReadFile" script.
User-inserted image

The first line in our script sets a variable named $filename equal to the path and file name of "c:\temp\myfile.txt" Then we see and "IF" clause that if the file and path can not be found, then print out on the screen "File does not exist", just as we saw when we ran the script a moment ago. The script is then halted.

This is a very good function to include when reading or writing files, because text files might get deleted or moved or just stuck depending on what you might be doing with files and how much you are using them. So making sure your script has an "out" method such as this to check the path and halt the program. It is a smart way to address any issues that might come up when working with text files.

Before going further, lets make sure you have created a temp folder on your c:\ drive.
User-inserted image

Now create a text file in the folder, by right clicking in the folder and select Text Document.
User-inserted image

Name the file "myfile".
User-inserted image

Now enter some lines of text in the file and be sure to save it!
User-inserted image

Now lets run the "ReadFile" script again. You should get the following successfully outcome from reading the file. Each line should be read and output until the end of the file is reached.
User-inserted image