24 total
By the end of this topic, you should be able to:
File handling is the use of programming techniques to work with information stored in text files on your computer. Think of it like a program being able to open a notebook, read what's written inside, add new notes, and then close it safely.
When you write a program, you often need to save information so that it's still there even after the program stops running. This is where file handling comes in.
There are several important reasons why programs need to store data in files:
1. Permanent storage
When your program finishes running, any variables you created disappear from memory. Files let you save data permanently on your hard drive, so it's still there the next time you run the program.
Example: A game that saves your high score, or a to-do list app that remembers your tasks even after you close it.
2. Large amounts of data
Files can hold much more information than you could type into a program every time you run it. Instead of asking the user to type in 1,000 customer names every time, you can read them from a file.
3. Sharing data between programs
Different programs can read and write to the same file. For example, one program might collect data and save it to a file, and another program can read that file and analyze the data.
4. Creating records
Files provide a permanent record of what happened. For example, a program might write a log file that records every action it took, which can be useful for finding errors later.
There are four main things you need to do when working with files:
Before you can read from or write to a file, you must open it first. When you open a file, you need to specify what you want to do with it — this is called the file mode.
There are three main file modes:
| Mode | Letter | What it does | When to use it |
|---|---|---|---|
| Read | "r" | Opens the file for reading only | When you only want to look at data that's already in the file |
| Write | "w" | Opens a new file for writing. Warning: If the file already exists, this will delete all the old content! | When you want to create a brand new file or completely replace an old one |
| Append | "a" | Opens an existing file and lets you add new data to the end | When you want to add new information without deleting what's already there |
Python example:
file = open("students.txt", "r") # Open for reading
file = open("students.txt", "w") # Open for writing (deletes old content!)
file = open("students.txt", "a") # Open for appending (adds to the end)
Pseudocode example:
OPENFILE "students.txt" FOR READ
OPENFILE "students.txt" FOR WRITE
OPENFILE "students.txt" FOR APPEND
Important: Always make a backup of important files before writing to them. One mistake with "w" mode and you could lose everything!
Once a file is open in read mode, you can get information out of it.
Reading a single line of text:
The readline() command (in Python) or READFILE command (in pseudocode) reads one line of text from the file. Think of it like reading one sentence at a time from a page.
Python example:
file = open("fruit.txt", "r")
line = file.readline() # Reads the first line
print(line)
file.close()
Pseudocode example:
OPENFILE "fruit.txt" FOR READ
READFILE "fruit.txt", LineOfText
OUTPUT LineOfText
CLOSEFILE "fruit.txt"
Reading multiple lines:
To read all the data in a file, you need to keep reading lines until you reach the end. You can use a loop (a section of code that repeats) to do this.
Python example:
file = open("employees.txt", "r")
endOfFile = False
while not endOfFile:
name = file.readline().strip()
if name == "": # Empty string means we've reached the end
endOfFile = True
else:
print("Name:", name)
file.close()
What is .strip()?
When you read a line from a file, it often includes extra spaces or a "newline" character (the invisible character that creates a new line). The strip() method removes these extra characters, giving you just the actual text.
In pseudocode, you use TRIM() to do the same thing:
name ← TRIM(name)
When a file is open in write mode or append mode, you can put new information into it.
Writing a single line of text:
The write() command (in Python) or WRITEFILE command (in pseudocode) writes data to the file.
Python example:
file = open("fruit.txt", "w")
file.write("Oranges")
file.close()
Pseudocode example:
OPENFILE "fruit.txt" FOR WRITE
WRITEFILE "fruit.txt", "Oranges"
CLOSEFILE "fruit.txt"
Writing multiple lines:
To write data on separate lines, you need to include a newline character (\n in Python, or NEWLINE in pseudocode).
Python example:
file = open("employees.txt", "a")
file.write("Polly\n") # Name
file.write("Sales\n") # Department
file.write("26000\n") # Salary
file.write("32\n") # Age
file.close()
Pseudocode example:
OPENFILE "employees.txt" FOR APPEND
WRITEFILE "employees.txt", "Polly"
WRITEFILE "employees.txt", NEWLINE
WRITEFILE "employees.txt", "Sales"
WRITEFILE "employees.txt", NEWLINE
WRITEFILE "employees.txt", "26000"
WRITEFILE "employees.txt", NEWLINE
WRITEFILE "employees.txt", "32"
WRITEFILE "employees.txt", NEWLINE
CLOSEFILE "employees.txt"
When you're finished working with a file, you must close it. This is important because:
Python example:
file.close()
Pseudocode example:
CLOSEFILE "students.txt"
Important rule: Every file you open must be closed! Always close your files when you're done with them.
Let's look at a complete example that reads employee information from a file.
The file (employees.txt) contains:
Greg
Sales
39000
43
Lucy
Human resources
26750
28
Jordan
Payroll
45000
31
Each employee has four lines of data: name, department, salary, and age.
Python program to read this data:
# Open file in read mode
file = open("employees.txt", "r")
endOfFile = False
while not endOfFile:
name = file.readline().strip() # Read line 1
department = file.readline().strip() # Read line 2
salary = file.readline().strip() # Read line 3
age = file.readline().strip() # Read line 4
if name == "": # Check if we've reached the end
endOfFile = True
else:
print("Name:", name)
print("Department:", department)
print("Salary:", salary)
print("Age:", age)
print() # Blank line for readability
# Close the file
file.close()
How this works:
Now let's add a new employee to the same file.
Python program to add data:
# Open file in append mode (adds to the end)
file = open("employees.txt", "a")
# Write new employee details
file.write("Polly\n") # Name
file.write("Sales\n") # Department
file.write("26000\n") # Salary
file.write("32\n") # Age
# Close the file
file.close()
After running this program, the file now contains all the original employees plus Polly at the end.
Sign in to view full notes