Exam code:1CP2
Programming File Handling
What is file handling?
-
File handling is the use of programming techniques to work with information stored in text files
-
Examples of file handing techniques are:
-
opening text files
-
reading text files
-
writing text files
-
closing text files
-
|
Concept |
Python |
|---|---|
|
Open |
|
|
Close |
|
|
Read line |
|
|
Write line |
|
|
End of file |
|
|
Create a new file |
|
|
Append a file |
|
-
The same approach for opening and writing to comma separated value files (CSV) can be used
-
When opening a CSV file, the file extension would change to “.csv“
-
file = open("fruit.csv","r")
-
What are the differences when file handling?
|
Concept |
What it means |
|---|---|
|
Open |
|
|
Close |
|
|
Read |
|
|
Write |
|
|
Append a file |
|
Python example (reading data from a text file)
|
Employees |
Text file |
|---|---|
|
|
Greg |
Python example (reading data from a csv file)
|
Employees |
CSV file |
|---|---|
|
# Open the CSV file
|
Greg, Sales, 39000, 43 |
Python example (writing new data to a text file)
|
Employees |
Text file |
|---|---|
|
|
Greg |
Python example (writing new data to a csv file)
|
Employees |
CSV file |
|---|---|
|
# Sample data to write to CSV
# Write data to CSV file
|
John, Sales, 50000, 30, Jane, Marketing, 60000, 35 Alice, Engineering, 70000, 40 |
Examiner Tips and Tricks
When opening files it is really important to make sure you use the correct letter in the open command
-
“r” is for reading from a file only
-
“w” is for writing to a new file, if the file does not exist it will be created. If a file with the same name exists the contents will be overwritten
-
“a” is for writing to the end of an existing file only
Always make a backup of text files you are working with, one mistake and you can lose the contents!
Worked Example
Use pseudocode to write an algorithm that does the following :
-
Inputs the title and year of a book from the user.
-
Permanently stores the book title and year to the existing text file books.txt [4]
How to answer this question
-
Write two input statements (title and year of book)
-
Open the file
-
Write inputs to file
-
Close the file
Example answer
title = input("Enter title")
year = input("Enter year")
file = open("books.txt")
file.writeline(title)
file.writeline(year)
file.close()
Marks
-
title = input("Enter title")1 mark for both-
year = input("Enter year")
-
-
file = open("books.txt")1 mark -
file.writeline(title)1 mark for both-
file.writeline(year)
-
-
file.close()1 mark
Responses