COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
8.3 | FILE HANDLING
Topics from the Cambridge IGCSE (9-1) Computer Science 0984 syllabus 2023 - 2025
ON THIS PAGE
SECTION 1 | WHAT IS FILE HANDLING
​SECTION 2 | READING FROM A TEXT FILE
​SECTION 3 | WRITING TO A TEXT FILE
​SECTION 4 | CLOSING A FILE
​SECTION 5 | COPYING TEXT BETWEEN FILES
SECTION 6 | READ/WRITE - WORD, LINE, DOCUMENT
MULTIPLE CHOICE QUESTIONS
​​SECTION 7 | FILE HANDLING WITH SPREADSHEETS / CSV FILES
ALSO IN THE TOPIC
 8.1 PROGRAMMING CONCEPTS
 8.1 PROGRAMMING CONCEPTS CONTINUED

 8.2 ARRAYS
 YOU ARE HERE | 8.3 FILE HANDLING
Picture

EXTERNAL FILE HANDLING

SECTION 1 | WHAT IS FILE HANDLING
​File handling refers to the process by which a computer program interacts with files stored on a disk, enabling the reading, writing, and modification of data. Unlike data stored in standard arrays, which are temporary and reset every time a program restarts, files provide a way to preserve data persistently across multiple runs of an application. This is crucial for applications that require long-term data storage, such as user settings, game scores, or transaction logs.

In programming languages like Python, file handling is straightforward yet powerful. Python uses simple commands to open, read, write, and close files, making it an ideal learning tool for students transitioning from temporary data storage in arrays to more permanent solutions. For example, to write data to a file, a Python program might open a file in write mode ('w'), write strings directly to the file, and then close it to ensure the data is saved:
  • PSEUDOCODE
  • PYTHON
<
>
​DECLARE DataToStore : STRING
DataToStore ← "Have a great day."

OPENFILE "data.txt" FOR WRITE
WRITEFILE "data.txt", DataToStore
CLOSEFILE "data.txt"
​with open('data.txt', 'w') as file:
    file.write('Have a great day.')
This code snippet opens data.txt (or creates it if it doesn't exist), writes a line of text, and automatically closes the file when done. The use of files allows data to be retained after the program closes, providing a durable means of storing information that can be retrieved and manipulated in subsequent program executions. This concept of persistent storage is fundamental for developing applications that interact with user data or require the retention of operational data over time.
SECTION 2 | READING FROM A TEXT FILE
To read data from a file, you must first open it in READ mode. Once opened, you can read the data using:
  • PSEUDOCODE
  • PYTHON
<
>
​DECLARE MyData : STRING
OPENFILE "data.txt" FOR READ
READFILE "data.txt", MyData
CLOSEFILE "data.txt"
# Open the file "data.txt" in read mode and read from it
with open("data.txt", "r") as file:
    my_data = file.read()

# Output the data read from the file
print(my_data)
SECTION 3 | WRITING TO A TEXT FILE
​To write data to a file, open it in WRITE mode. Any existing content in the file will be erased. To write, use:
  • PSEUDOCODE
  • PYTHON
<
>
​DECLARE MyData : STRING
MyData ← "Hello, world!"
OPENFILE "output.txt" FOR WRITE
WRITEFILE "output.txt", MyData
CLOSEFILE "output.txt"
# Open the file "output.txt" in write mode and write to it
with open("output.txt", "w") as file:
    file.write("Hello, world!")
SECTION 4 | CLOSING A FILE
​After completing the read or write operations, it is good practice to close the file:
  • PSEUDOCODE
<
>
​CLOSEFILE "output.txt"
SECTION 5 | COPYING TEXT BETWEEN FILES
​Consider a scenario where you need to copy a line of text from one file to another:
  • PSEUDOCODE
  • PYTHON
<
>
​DECLARE LineOfText : STRING
OPENFILE "FileA.txt" FOR READ
OPENFILE "FileB.txt" FOR WRITE
READFILE "FileA.txt", LineOfText
WRITEFILE "FileB.txt", LineOfText
CLOSEFILE "FileA.txt"
CLOSEFILE "FileB.txt"
​# Open "FileA.txt" for reading
with open("FileA.txt", "r") as file_a:
    line_of_text = file_a.read()  # Read all content from FileA

# Open "FileB.txt" for writing
with open("FileB.txt", "w") as file_b:
    file_b.write(line_of_text)  # Write the content to FileB
SECTION 6 | READ/WRITE - WORD, LINE, DOCUMENT
Here, we explore the concepts of reading and writing by word, by line, and by the entire document, and how these operations are typically implemented in programming.

Reading and Writing a Word
When you read or write a word from a file, you are typically interacting with the smallest unit of meaningful text separated by spaces or punctuation. This level of granularity is useful for text analysis, such as counting word frequency or replacing specific words.

READING A WORD
  • PSEUDOCODE
  • PYTHON
<
>
OPENFILE "file.txt" FOR READ
DECLARE words : LIST OF STRING
READFILE "file.txt", words  // Assuming the entire file is read and split into words
FOR EACH word IN words
    OUTPUT word
ENDFOR
CLOSEFILE "file.txt"
with open("file.txt", "r") as file:
    words = file.read().split()  # This reads the entire content and splits it by whitespace
    for word in words:
        print(word)  # This prints each word separately
WRITING A WORD
  • PSEUDOCODE
  • PYTHON
<
>
DECLARE word : STRING
word ← "Hello"
OPENFILE "file.txt" FOR WRITE
WRITEFILE "file.txt", word + " "  // Adds a space after the word
CLOSEFILE "file.txt"
​with open("file.txt", "w") as file:
    word = "Hello"
    file.write(word + " ")  # Writes a single word to the file, followed by a space
Reading and Writing a Line
Lines represent a sequence of characters ending with a newline character (\n). Handling data line by line is one of the most common forms of file manipulation, used for reading configuration files, logs, or any data structured into rows.

READING A LINE
  • PSEUDOCODE
  • PYTHON
<
>
​OPENFILE "file.txt" FOR READ
DECLARE line : STRING
WHILE NOT EOF("file.txt")  // Loop until the end of the file
    READFILE "file.txt", line
    OUTPUT line
ENDWHILE
CLOSEFILE "file.txt"
​with open("file.txt", "r") as file:
    for line in file:
        print(line.strip())  # `strip` removes the newline character at the end of each line
WRITING A LINE
  • PSEUDOCODE
  • PYTHON
<
>
​DECLARE line : STRING
line ← "This is a line of text\n"
OPENFILE "file.txt" FOR WRITE
WRITEFILE "file.txt", line
CLOSEFILE "file.txt"
​with open("file.txt", "w") as file:
    line = "This is a line of text\n"
    file.write(line)  # Writes the line including the newline character to delineate lines
Reading and Writing the Entire Document
Sometimes, it's necessary to work with the entire content of a document at once, such as when loading configuration settings or processing small files where it's efficient to work with all the data in memory.

READING THE DOCUMENT
  • PSEUDOCODE
  • PYTHON
<
>
​OPENFILE "file.txt" FOR READ
DECLARE content : STRING
READFILE "file.txt", content  // Reads the entire file into 'content'
OUTPUT content
CLOSEFILE "file.txt"
with open("file.txt", "r") as file:
    content = file.read()  # Reads the entire file into a single string
    print(content)
WRITING THE DOCUMENT
  • PSEUDOCODE
  • PYTHON
<
>
​DECLARE content : STRING
content ← "This is the entire content of the file."
OPENFILE "file.txt" FOR WRITE
WRITEFILE "file.txt", content
CLOSEFILE "file.txt"
​with open("file.txt", "w") as file:
    content = "This is the entire content of the file."
    file.write(content)  # Writes a large block of text to the file
MULTIPLE CHOICE QUESTIONS
1: What does the OPENFILE command do in file handling?
A) Closes the file
B) Reads data from the file
C) Opens the file for reading, writing, or both
D) Deletes the file

2: When opening a file for writing using OPENFILE "data.txt" FOR WRITE, what happens if "data.txt" already exists?
A) The file is deleted and a new empty file is created.
B) The file cannot be opened unless it is empty.
C) Data will be appended to the existing data.
D) The file is opened normally with no changes to existing data.

3: Which command reads data from an open file into a variable?
A) OPENFILE
B) READFILE
C) WRITEFILE
D) CLOSEFILE

4: Why is it important to close a file after operations are completed?
A) To save the data written to the file
B) To free up system resources
C) Both A and B
D) Closing a file is optional and does not impact the system or data.

5: In file handling, what does EOF stand for, and why is it significant?
A) End Of File, it indicates that there is no more data to read from the file.
B) Execution Of File, it indicates that the file is currently being executed.
C) Each Open File, a reference to all open files in a program.
D) Error On File, an error message that occurs when a file cannot be accessed.

6: Which file mode should be used if you need to both read from and write to the same file without deleting its contents?
A) READ
B) WRITE
C) APPEND
D) READ/WRITE
​
7: What is a potential consequence of not closing a file in a program?
A) The data might not be properly saved to the file.
B) The program might use more memory than necessary.
C) Other programs might not be able to open the file.
D) All of the above.

8: How can you ensure data is read one line at a time from a file?
A) Use READFILE <File Identifier>, <Variable> and specify you want lines.
B) Read the entire file and split the data into lines in the program.
C) Use a loop to read until EOF, capturing data line by line.
D) It's not possible to read data one line at a time.

9: What is the correct way to write the string "Hello World" to a new file called "greetings.txt"?
A) OPENFILE "greetings.txt" FOR WRITE then WRITEFILE "Hello World"
B) WRITEFILE "greetings.txt", "Hello World" without opening the file.
C) OPENFILE "greetings.txt" FOR WRITE then WRITEFILE "greetings.txt", "Hello World" then CLOSEFILE "greetings.txt"
D) WRITEFILE "greetings.txt", "Hello World" then CLOSEFILE "greetings.txt"
​
10: Which of the following is true about the WRITEFILE command?
A) It can be used without opening the file first.
B) It appends the data to the end of the file by default.
C) It overwrites the existing content unless the file is opened in append mode.
D) It reads data from the file and writes it to another file.
SECTION 7 | FILE HANDLING WITH SPREADSHEETS / CSV FILES
CSV (Comma Separated Values) files are commonly used to store tabular data. These files are straightforward to read from and write to because their data is separated by commas, making parsing simple. In computer programming, handling CSV files efficiently can be crucial for data processing tasks such as database uploads, data analysis, and report generation. Here, we'll explore how to perform basic operations such as reading, writing, appending, and modifying data in CSV files.

READING FROM A CSV FILE
  • PSEUDOCODE
  • PYTHON
<
>
​OPENFILE "data.csv" FOR READ
DECLARE row : STRING
WHILE NOT EOF("data.csv")
    READFILE "data.csv", row
    OUTPUT row  // Prints each row of the CSV file
ENDWHILE
CLOSEFILE "data.csv"
import csv

with open('data.csv', 'r', newline='') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)  # Each row is a list of values
WRITING TO A CSV FILE
  • PSEUDOCODE
  • PYTHON
<
>
​OPENFILE "new_data.csv" FOR WRITE
DECLARE dataRow : STRING
dataRow ← "Name,Age,Location"
WRITEFILE "new_data.csv", dataRow
CLOSEFILE "new_data.csv"
​import csv

with open('new_data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'Location'])  # Write a header row
APPENDING A CSV FILE

Appending to a CSV file involves adding new rows of data without overwriting existing data.
  • PSEUDOCODE
  • PYTHON
<
>
​OPENFILE "data.csv" FOR APPEND
DECLARE newRow : STRING
newRow ← "John,30,New York"
WRITEFILE "data.csv", newRow
CLOSEFILE "data.csv"
​import csv

with open('data.csv', 'a', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['John', 30, 'New York'])  # Append a new row
MODIFYING A CSV FILE

Modifying a CSV file generally involves reading the existing data, making changes, and then writing the data back to the file.
  • PSEUDOCODE
  • PYTHON
<
>
​OPENFILE "data.csv" FOR READ
DECLARE allRows : LIST OF STRING
DECLARE row : STRING
WHILE NOT EOF("data.csv")
    READFILE "data.csv", row
    IF row CONTAINS "OldLocation"
        REPLACE "OldLocation" WITH "NewLocation" IN row
    ENDIF
    APPEND row TO allRows
ENDWHILE
CLOSEFILE "data.csv"

OPENFILE "data.csv" FOR WRITE
FOR EACH row IN allRows
    WRITEFILE "data.csv", row
ENDFOR
CLOSEFILE "data.csv"
​import csv

# Read all data
data = []
with open('data.csv', 'r', newline='') as file:
    reader = csv.reader(file)
    for row in reader:
        data.append(row)

# Modify data
for row in data:
    if 'OldLocation' in row:
        index = row.index('OldLocation')
        row[index] = 'NewLocation'

# Write data back
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    for row in data:
        writer.writerow(row)
EXAMINATION STYLE QUESTIONS
1: What does the following block of pseudocode do?

DECLARE FileReader : FILE
OPENFILE "journal.txt" FOR READ
DECLARE LineCount : INTEGER
LineCount ← 0
DECLARE Line : STRING

READFILE "journal.txt", Line
WHILE NOT Line = ""
    LineCount ← LineCount + 1
    READFILE "journal.txt", Line
ENDWHILE

OUTPUT "Number of lines in the file: ", LineCount
CLOSEFILE "journal.txt"
​A) Counts the number of words in journal.txt
B) Counts the number of characters in journal.txt
C) Counts the number of lines in journal.txt
D) Copies the content of journal.txt to another file

2: Write pseudocode to append the text "Remember to subscribe!" to the end of an existing text file named "notes.txt".

3: Examine the following pseudocode and explain what it accomplishes.
OPENFILE "report.txt" FOR WRITE
FOR i FROM 1 TO 100
    WRITEFILE "report.txt", "Line ", i
ENDFOR
CLOSEFILE "report.txt"

4: Identify the error in the following pseudocode that intends to read each word from data.txt and print it.
OPENFILE "data.txt" FOR READ
DECLARE Word : STRING

READFILE "data.txt", Word
WHILE NOT Word = ""
    OUTPUT Word
    READFILE "data.txt", Word
ENDWHILE

CLOSEFILE "data.txt"

5: ​Given the scenario where a student needs to save their daily expenses into a file named "expenses.txt", write pseudocode that allows the user to enter their expenses one at a time and save each entry on a new line in the file until the user types "stop".
Picture
ALSO IN THIS TOPIC
 8.1 PROGRAMMING CONCEPTS
 8.1 PROGRAMMING CONCEPTS CONTINUED

 8.2 ARRAYS
 8.3 FILE HANDLING
TOPIC 8 ANSWERS
​
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.