3.2.5 Input, Output and File Handling

Table of Contents

Fork me on GitHub

1 Input and Output

Input_Output_Main.png

Learn It: What is input and output?

Input and Output – An input device sends information to a computer system for processing,
and an output device reproduces or displays the results of that processing. Most devices
are only input devices or output devices, as they can only accept data input from a user
or output data generated by a computer. However, some devices can accept input and display
output, and they are referred to as I/O devices (input/output devices).
  • Computer programs take inputs, process data and produce outputs.
  • The inputs to a program can originate from many locations:
    • Keyboard,
    • Microphone,
    • Mouse,
    • Motion sensor,
    • Heat sensor,
    • An input stream over a network,
    • Digital camera,
    • Another file,
    • Touch/Graphics Pad,
    • Bar code reader.
  • However, the standard form of input is from a keyboard.

  • Likewise, data can be output to many devices:
    • VDU/Display,
    • Speakers,
    • Printers,
    • Another file,
    • Actuators,
    • Projectors.
  • But the standard form of output is the monitor (or screen).
  • We have used two commands that enable data to come in or go out of a program:
    • USERINPUT
    • OUTPUT
  • Because the monitor and keyboard are considered standard input and output respectively, it is assumed that the data for USERINPUT comes from the keyboard and the data for OUTPUT is displayed on a monitor.

User input from the keyboard

  • Throughout previous topics including this one, we have used an INPUT command in pseudocode and have expanded this slightly in Python to show the actual input message.

User_Input1.png

  • We can use data type to make the input command more specific.

User_Input2.png Displaying Output

  • Throughout this topic we have only used fairly simple OUTPUT commands (known as a print command in Python).

User_Output1.png

  • However, this is not very user friendly and it is necessary to sometimes combine the output in a suitable message.

User_Output2.png

  • Notice that the + symbol is used in the pseudocode. When part of a statement is a string (in this case “Hello”) the + symbol is known as concatenation (or joining) which allows values to be joined together rather than added together.
  • By using a comma separator, Python will automatically add a space after the string.
  • If the data type of the variable is also a string, then we can use the + symbol concatenation.
  • If the variable is not a string, then we would need to cast the data type into a string using: print(“Hello “ +str(name))
  • Just remember the strings appear with speech marks.

User_Output3.png User_Output4.png Formatting Output

  • Python provides format operators to allow us to output data and information to a display in a clearer and more organised format.

The table below shows the most common formatting conversion character: Format_Conversion_Table.png The table below shows the most common format modifiers: Format_Modifier_Table.png

  • Format modifiers can be used to:
    • Specify a field width.
    • Specify the number of digits after the decimal point.
    • Left or right-justify a value with a specified field width.

  • The % operator is a string operator called the format operator.
  • Using the format operator, instead of writing something like:

London_Temp1.png

  • We can re-write the statement using format operators as:

London_Temp2.png

  • We can now incorporate the format operators with a user-friendly message as:

London_Temp3.png

  • The formatting above can be divided into two parts:
    • The first part, “%s, %d, %s”, contains one or more format specifications. A conversion character % tells the format operator what type of value is to be inserted into that position in the string; %s indicates a string, %d indicates an integer.
    • The second part, %(city, temperatureC, localTime), specifies the values that are to be printed.

Try It: Format Operators

  1. Write statements to do the following:
    • a) Set a=3, b=4, c= a + b, d = a*b.
  2. Use format operators to print the statements:
    • a) 3 + 4 = 7
    • b) The product of 3 and 4 is 12

Badge It: Pseudocode Challenge

Silver - Guessing Game

  1. Write a program for a guessing game (using pseudocode or flowchart) that does the following: (6 Marks)
    • a) Assigns the word "cat" to a variable called answer.
    • b) Assigns the user's input to a variable called guess.
    • c) If the user correctly guesses "cat" then the program outputs "Correct", otherwise the program lets the user guess again.
    • d) The program continues until the user guesses correctly.
  2. The programmer wants to improve the game. State two simple changes tha they could make to improve the it? (2 Marks)

Upload to Fundamentals of 3.2 Programming - 3.2.5 Input, Output and File Handling: Silver on BourneToLearn

2 File Handling

File_Handling_Main.png

Learn It: What is File Handling?

File – A store of data, used by a program, that continues to exist when the program or
computer is switched off. Many file formats exist, and the practical aspects of this
section will deal with text (.txt) files, typically associated with a program
called 'Notpad'.
  • Often, this data will need to be stored in a file which can be held permanently on storage media, from where it can be read the next time it is needed.
  • We will need to write a program that will save the data between the running of the program and this is known as a persistent data storage system.
  • We will look at how this data can be stored outside of the program in a text file (.txt) which can be read by many different applications.
  • Text files contains text that is in lines. There is no other structure, unlike files of records.
In many programming languages, you will have to follow a set of steps to access the data
in a text file as follows:
1. Tell the program where the file is.
2. Open the file to read in from it.
3. Read a line/lines of text from the file.
4. Close the file.
Writing to a file has similar steps:
1. Open the file to write to.
2. Write each line of text to the file one at a time, until there is no more text to write.
3. Remember to close the file at the end.

File Locations

  • Text files are referred to by their name countries.txt. If the file is stored in the same location as the program, then just the name of the file will be sufficient, but if the file is stored in another folder on your computer/network you will need to use the full file name including the root address of where the file is stored as shown below:
/students/user/astudent/compsci/countries.txt

Writing to a Text File

  • In order to write to a text file, all the data needs to be converted to a string. We will be looking at how to do this with other data types later but for now you just need the following:

Write_Test_File1.png

  • Note that the code is the same in both examples in Python, as it does not matter if the original number is an integer or a float number.
  • Look at some file handling pseudocode:

Write_Test_File2.png

  • This code will set a variable called country to England and another called population to 53 million.
  • It will then open a file called countries; if there is not one already in existence the file will be created.
  • Then a new variable is created called newData which will join the country (England) to the population (53 million) which is converted to a string.
  • This data is then written to the countries text file and the file is closed.

It works in a similar way in Python: Write_Test_File3.png

  • The country is assigned the value England and the population is 53 million. The next line is different. Not only do you need to tell Python which file to open, you also need to specify how that file will be used.

File Handling Table File_Handling_Table.png

  • In the example previously shown, we have specifyied w after the file name so the file will be created.
  • The data is joined together and the population converted to a string and assigned to the variable newData and there is an additional element (+”/n). This is a line break, so that if we were to add an additional line it would appear on the next line in the text file.
  • This makes it easier later if we want to display the data on separate lines in Python.
  • The data is written to the text file and the file is closed.
  • It is very important the file is closed,* as this is when Python *saves the changes to the file and if the file is not closed the new data will not be written to the file.
  • If you wanted to add additional rows of data to Python you would not use the w character at the end of the open line,* as this will overwrite the *original data. Instead you would use the a character to add additional lines as shown below:

Write_Test_File4.png

  • *This is the same program but adapted slightly so that the user can enter the country and population and the data will be added to the existing file rather than overwriting the existing file.*

Reading from a Text File

  • Using the write method we looked at previously, we added a comma between each bit of data and put each record on a separate line.
  • To read the file we can use the following pseudocode:

Read_Text_File1.png

  • This will display the data stored in the countries.txt file. If you wanted each row to appear on *a separate line,* you could use the line dataToRead ← READLINE(file) instead of dataToRead ← READ(file).
  • We can do a similar thing in Python:

Read_Text_File2.png

  • Note, Python does not need to use the while loop. Python will stop automatically when it gets to the end of the file.
  • The other difference is Python will automatically display each record on a separate row as the /n line break was used when the data was originally written.

More examples of File Handling More_File_Handling.png

Badge It: File Handling Challenge 1

Gold - Tom's Adventure Story

  1. Tom has written an adventure story in the file adventure.txt.
  2. Using the Trinket below, write a program that will allow a user to output Tom's adventure story one line a time.
  3. Each time the user presses the "y" key, the next line of the story should be outputted.
  4. The algorithm should end and close the file when it outputs the string "THE END".

Upload to Fundamentals of 3.2 Programming - 3.2.5 Input, Output and File Handling: Gold on BourneToLearn

Badge It: File Handling Challenge 2

Platinum - Even and Odd Numbers

  1. Create a Python program which will ask the user to enter 10 numbers. If the number is an even number (i.e. when it is divided by 2 there is no remainder) add it to a text file called even.txt. If it is an odd number add it to the file called odd.txt.
  2. Once they have entered all 10 numbers it should ask them if they want to see the odd or the even numbers and display the numbers from the correct file.
  3. Use subroutines to split the code into manageable chunks. Use this page to make notes and scribbles that you think may help you with creating the program.

Upload to Fundamentals of 3.2 Programming - 3.2.5 Input, Output and File Handling: Platinum on BourneToLearn

Validate