Introduction to File Handling and Input Validation
In our previous chapters, we learned how to store data in variables and arrays. However, there is a catch: as soon as you turn off your computer or stop your program, that data disappears! This is because variables live in the computer's temporary memory (RAM). To keep data permanently, we need File Handling.
Additionally, we need to make sure the data we get from users is "good" data. If a program expects a number but gets a word, it might crash. This is why we use Input Validation. In this chapter, we will learn how to make our programs more professional, reliable, and "persistent" (meaning the data sticks around!).
1. File Handling: Persistent Storage
File handling allows a program to interact with files stored on the hard drive or SSD. Think of it like a librarian: to get information, you must first find the book, open it, read it, and then—importantly—put it back (close it).
The Three Basic Steps
Whenever you work with files in programming, you follow this standard sequence:
- Open: Establish a connection between your program and the file.
- Process: Either Read from the file (take data out) or Write to the file (put data in).
- Close: Disconnect the program from the file. This is crucial because it saves changes and frees up memory.
File Modes
When you open a file, you have to tell the computer what you intend to do with it. This is called the "mode":
- Read Mode: You only want to see what is inside. You cannot change anything.
- Write Mode: You want to create a new file or overwrite everything in an existing file. Warning: This usually deletes the old content!
- Append Mode: You want to add new data to the end of the existing content without deleting anything.
Did you know? If you forget to close a file, your computer might "lock" it, preventing other programs from using it, or you might lose the data you just tried to save!
Quick Review: File Handling Basics
Key Takeaway: Files provide persistence. Without file handling, data is lost when the program ends. Always remember the cycle: Open \(\rightarrow\) Process \(\rightarrow\) Close.
2. Input Validation: The "GIGO" Principle
In Computer Science, there is a famous saying: "Garbage In, Garbage Out" (GIGO). This means that if a user enters "garbage" (bad data), your program will produce "garbage" results or simply crash.
Input Validation is a defensive programming technique. It is the process of checking that the data entered by a user (or read from a file) meets certain criteria before the program processes it.
Common Types of Validation Checks
To keep our programs safe, we use several types of checks:
- Type Check: Ensures the data is the right "kind" (e.g., ensuring an age is an Integer, not a String).
- Range Check: Ensures a number falls between two boundaries (e.g., a month must be between \(1\) and \(12\)).
- Presence Check: Ensures the user didn't leave the input blank (e.g., a "Required" field on a form).
- Length Check: Ensures the input isn't too short or too long (e.g., a password must be at least \(8\) characters).
- Format Check: Ensures the data follows a specific pattern (e.g., an email address must contain an '@' symbol).
Analogy: Validation is like a bouncer at a club. The bouncer checks your ID (Type/Range check) and makes sure you are wearing shoes (Presence check) before letting you inside.
Validation vs. Verification
Students often confuse these two, but they are different!
- Validation: "Is this data sensible and allowable?" (Automatic check by the computer).
- Verification: "Is this data correct?" (Usually involves a human checking, like entering a password twice to make sure they match).
3. Implementing Validation Logic
In B.2 Programming, you will often need to write code that repeatedly asks a user for input until they provide something valid. We usually use a While Loop for this.
The "Input-Check-Repeat" Pattern:
- Ask the user for input.
- Start a While loop that runs if the input is invalid.
- Inside the loop, tell the user there was an error and ask them to try again.
- Once they enter valid data, the loop ends, and the program continues.
Example Logic:
Set age = get user input
While (age < 0 OR age > 120):
Print "Invalid age! Please enter a number between 0 and 120."
Set age = get user input
Print "Age accepted!"
Don't worry if this seems tricky: The key is to remember that the loop keeps running as long as the data is bad. As soon as the data is good, the loop condition becomes false, and the program moves on.
4. Common Mistakes to Avoid
- Forgetting to Close Files: Always pair every "Open" with a "Close." In Python, using the
withkeyword handles this for you automatically! - Wrong Mode: Using "Write" mode when you meant "Append" and accidentally erasing your entire database.
- Infinite Loops: Forgetting to update the input variable inside your validation loop, causing the program to ask the same question forever.
- Validation vs. Error Handling: Validation prevents the error from happening. Error handling (like Try/Catch) deals with errors after they happen. Both are useful!
Chapter Summary
Files: Used for persistent storage. Steps: Open, Read/Write, Close.
Modes: Read ('r'), Write ('w'), Append ('a').
Validation: Ensuring data is sensible before processing (GIGO).
Checks: Type, Range, Presence, Length, and Format.
Logic: Use a While loop to force the user to provide valid data.
Cross-reference: For more on how to handle errors when files are missing, see the chapter on "Tracing, debugging and testing code". For details on data types used in validation, see "Variables, data types and operators".