Opening and closing text files is one of the most common tasks a Python program does. It allows your code to store information permanently (like a score in a game) or to read data that already exists (like a list of names). For the PCEP-30-02 exam, you need to know exactly how to use open() and close() so your programs don't lose data or crash.
Jump to a section
A simple way to picture Simple File Operations
24 times in an hour, your office assistant needs to pull a client letter out of the filing cabinet, read the handwritten note at the bottom, then put it back.
The filing cabinet in your office is a lot like how Python handles text files. Each drawer is a folder on your computer. Each hanging file is a text file. But here is the crucial bit: before anyone can read or write to a file in that cabinet, they must first pull the drawer open. In Python, that is what the open() function does. It says, "I need access to this specific file." Once the drawer is open, your assistant can take a file out, read from it (like using the read() method to see all the text inside), or write a new note on it (like using write() to put new content in). When they are finished, they must close the drawer (using close()). If they leave the drawer open, someone else might trip over it, or more importantly, the office manager (the operating system) might get angry because too many drawers are open at once.
If you forget to close() the file drawer in Python, your program might not save the last sentence you wrote. Worse, it could lock the file so no other program can use it until your program crashes or finishes. That is why good Python programmers always close the drawer after they are done.
When a Python program runs, all its variables and data live in the computer's Random Access Memory (RAM). This memory is fast, but it is temporary. When the program ends or the computer shuts down, everything stored in RAM is lost forever. That is a big problem for programs that need to remember things, like a to-do list app that should still have your tasks tomorrow.
To solve this, we use files on the hard drive. A file is a container of data that stays even after the program stops. Text files are one of the simplest types of file. A text file contains only human-readable characters (letters, numbers, punctuation, and spaces) arranged in lines. Think of it like a plain digital notepad. The Python command to create or access a file is the open() function.
What is open()? The open() function is a built-in Python tool that tells the operating system, "I want to use this file." It takes two main pieces of information: the file's name (or full path, like a postal address for the file) and the mode of access. The mode tells Python what you plan to do with the file. The most common modes you need for PCEP-30-02 are:
'r' for reading. This opens the file so you can look at its contents. You cannot change anything. If the file does not exist, your program will crash.
'w' for writing. This opens the file so you can put new text into it. If the file already exists, this mode will completely erase the old content first. It is like throwing away the old notebook and starting a fresh one.
'a' for appending. This opens the file so you can add new text to the end of the existing content. The old stuff stays safe. If the file does not exist, it creates a new one.
'r+' for reading and writing. This opens the file so you can both look at content and change it. The file must already exist.
When you call open(), it returns a special object called a file object. You usually store this in a variable, like this: my_file = open("data.txt", "r"). This creates a file object called my_file that is connected to the file "data.txt" in read mode.
Reading from a text file Once the file object is created, you can use methods on it to get the text. The most common methods are: - .read() reads the entire file as a single string. Great for small files. - .readline() reads one line at a time. Each call returns the next line as a string. It includes the newline character at the end. - .readlines() reads all lines into a list of strings. Each list item is one line.
For example, if "notes.txt" contains "Hello
World", then content = my_file.read() would make content equal to the string "Hello
World".
Writing to a text file To write, you need a file opened in write ('w') or append ('a') mode. The main method is .write(). You pass it a string as an argument. For example: `my_file.write("First line ")` writes the text "First line" followed by a newline to the file. If the file is in write mode, this replaces everything. If it is in append mode, this adds to the end.
Closing the file
When you are done, you must call the .close() method on the file object: my_file.close(). This does two critical things. First, it tells the operating system that your program is finished with the file, freeing up resources. Second, and most importantly for writing, it forces Python to flush (empty) any data that was temporarily stored in a buffer (a short-term holding area) to the actual file on disk. If the program crashes before you call close(), the last bits of data that were written might stay in the buffer and be lost forever.
Why does this matter? Before files, every bit of information was locked inside the program and vanished when it ended. Files allow programs to store configuration settings, user data, logs, and reports permanently. For the PCEP exam, you must be able to write a small piece of code that opens a file, reads or writes a line, and then closes it. They will test whether you understand the difference between 'w' and 'a', and whether you know that forgetting to call close() is a bug that can lose data.
Choose your file and mode
Decide which text file you want to work with and what you want to do. Do you want to read it, overwrite it, or add to it? This determines the mode string ('r', 'w', or 'a'). This step is crucial because picking the wrong mode can accidentally delete data.
Call open()
Use the open() function with the filename (as a string) and the mode string. For example, `f = open("myfile.txt", "r")`. This returns a file object that acts as your connection to the file on disk.
Perform the operation (read or write)
Call the appropriate method on the file object. For reading, use .read() to get the whole file, .readline() to get one line, or .readlines() to get all lines as a list. For writing, use .write() with the string you want to add. Remember: in 'w' mode, .write() replaces everything.
Save your work by calling close()
Call the .close() method on the file object. This forces Python to write any buffered data to the disk and releases the file handle back to the operating system. Without this step, your changes might not be saved.
Test that the file looks correct
After closing the file, you can open it again in read mode and print its content to verify that the operation worked as expected. This step helps you catch bugs early, such as forgetting the newline character at the end of a write.
An IT professional working for a small e-commerce company might need to write a Python script that logs every order placed on the website. Every time a customer completes a purchase, the script must add a new line to a text file called "orders.txt". This file is then used by another system to prepare shipments.
Here is the real-world scenario step-by-step:
1. The web application sends a notification to a Python script with the order details: order number, customer name, item, and total price.
2. The Python script needs to store this information permanently. It cannot just keep it in RAM because if the script restarts, that order would be lost and the company would miss the sale.
3. The script makes the decision about which mode to use. It cannot use 'w' because that would erase all previous orders. It uses 'a' (append mode) so the new order is added to the end of the existing list.
4. The script calls log_file = open("orders.txt", "a") to get a file object.
5. It creates a string containing the order details, for example: "2024-03-15, Order# 543, Alice, Widget, $12.99
"
6. It writes this string to the file using log_file.write(line).
7. Immediately after writing, it calls log_file.close(). If the script forgot to close, and the server lost power right after the write but before the buffer was flushed, the order would not appear in the log, and the item would never be shipped. The customer would be angry.
The IT professional also uses file operations for:
Reading configuration files that hold settings like database addresses and usernames, so the program can adapt to different environments without changing the code.
Writing error logs to text files for debugging. When something breaks, the text file contains the exact error message and the time it happened.
Importing lists of email addresses from a text file to send a newsletter. They open the file in read mode, use .readlines() to get every address, then loop over the list to send the emails.
In all these cases, the pattern is exactly the same: open the file in the correct mode, do the reading or writing, and then close the file. IT professionals often use the with statement in real code (which automatically closes the file), but for the PCEP-30-02 exam, you will be tested on the explicit open() and close() pattern.
The PCEP-30-02 exam tests your ability to perform basic file operations exactly as they are defined in the Python language specification. You will not be asked to manage complex file paths or to handle large datasets. The questions focus on the mechanics of open(), close(), and the basic read and write methods.
Here are the exact concepts and question types you must master:
Mode strings: They will show you a line of code like f = open("data.txt", "x") and ask you what x does (x is actually 'w', 'a', or 'r'). You must know that 'w' overwrites, 'a' appends, and 'r' reads. They love to test 'w' vs 'a' because beginners always confuse them.
File existence errors: If you try to open a file for reading ('r') and the file does not exist, Python raises a FileNotFoundError. The exam expects you to know this. They might give you code that opens a non-existent file and ask what happens.
Buffer flushing and close(): They will test whether you understand that not calling close() can lead to lost data when writing. A common exam question says, "What happens if you write to a file and then the program ends without calling close()?" The correct answer: the written data might be lost from the buffer.
Return type of read(): They ask what type of value .read() returns (a string). Similarly, .readlines() returns a list of strings.
Binary vs text mode: The exam sometimes tests that by default, open() opens a file in text mode ('t'). But you also need to know about binary mode ('b'), which is used for non-text files like images. A trick question might show open("file", "rb") and ask what that means.
Common traps and how to avoid them:
Trap: A question describes opening a file with 'w' mode and using .read(). This will throw an error because 'w' mode does not allow reading. The correct action is to remember that mode restricts which operations are valid.
Trap: They show two code snippets: one that opens a file, writes to it, and closes it, and another that opens a file, writes to it, but does not close it. They ask which one is correct. The answer is the one that calls close().
Trap: They state that the file object returned by open() has a method called .append(). That is false. The method is .write().
Trap: They ask how to read the first line of a file. Beginners might say .readlines()[0], but the correct method is .readline().
Key definitions to memorise for the exam:
File object: The object returned by open(). It provides methods like .read(), .write(), .close().
Mode: The second argument to open(), a string like 'r', 'w', 'a', 'r+', 'wb'.
flush: The act of moving data from a temporary buffer to the permanent storage. The .close() method triggers a flush.
Buffer: A temporary memory area where data is held before being written to disk. Buffers improve performance.
To prepare for the exam, practise writing small scripts that:
Write three lines to a file, then close it.
Read all lines from a file using .readlines() and print them.
Open a file in append mode and add one more line.
Predict what will happen when you try to read from a file in write mode.
Always call .close() on a file object after you finish reading or writing, or data can be lost and system resources wasted.
The 'w' mode erases the file and starts fresh, while 'a' mode preserves the existing content and adds new text at the end.
If you try to open a file in 'r' mode and the file does not exist, Python raises a FileNotFoundError.
The .read() method returns the entire file content as a single string, including newline characters.
The .readlines() method returns a list of strings, where each element is one line from the file.
You cannot use .write() on a file opened in 'r' mode; you must open it in 'w', 'a', or 'r+' mode to write.
These come up on the exam all the time. Here's how to tell them apart.
Read mode ('r')
Opens file for reading only; writing is forbidden
Raises FileNotFoundError if file does not exist
Content of file remains unchanged after operation
Write mode ('w')
Opens file for writing; reading is forbidden
Creates a new file if it does not exist
Erases all existing content before writing new data
Write mode ('w')
Overwrites the entire file each time you open it
Useful for replacing old data with new data
Always starts writing at the beginning of the file
Append mode ('a')
Adds new content to the end of the existing file
Useful for adding log entries without losing history
Starts writing at the current end of the file
.read() method
Returns the entire file content as a single string
Reads all content into memory at once
Includes newline characters in the returned string
.readlines() method
Returns a list of strings, one per line
Each element in the list is one line of the file
Each line string includes the trailing newline character
Mistake
You do not need to close a file if you are only reading from it, because you are not changing anything.
Correct
You must always close a file, even when reading. Every open file uses system resources. If you open many files without closing, you can run out of file handles, causing your program to crash.
Beginners think 'close' is only for saving. They do not realise that every open() reserves a limited resource from the operating system.
Mistake
Opening a file with 'w' mode and then writing adds the new content to the end of the file.
Correct
The 'w' mode overwrites the entire file. It deletes all existing content first. If you want to add to the end, you need 'a' (append) mode.
The word 'write' sounds like it means 'add text', but in Python, 'write' mode means 'write from the start, replacing everything'.
Mistake
The file object returned by open() contains the text of the file directly as a string.
Correct
The file object is a handle, not the content. You must call .read() or .readline() on the file object to actually get the text from the file.
Beginners expect that assigning the result of open() to a variable would instantly load the file content into that variable. They confuse the file object with a string.
Mistake
If you write to a file and your program ends normally, the data is always saved safely even if you forgot to call close().
Correct
It is not guaranteed. Python only flushes the buffer when close() is called or when the buffer is full. If the program ends normally, the buffer might still be partially written. The only safe way is to call close() explicitly.
Many beginners assume that ending the program automatically saves everything, like closing a document in a word processor. But Python does not auto-save for every buffer.
Mistake
You can open a file in read mode and still write to it by using the .write() method.
Correct
If you open a file with 'r' mode, only reading methods like .read() and .readline() are allowed. Calling .write() will raise an io.UnsupportedOperation error.
Beginners do not think of modes as strict contracts. They assume once a file is 'open', all operations are possible.
Reveal each answer, then mark whether you got it right. Score 60%+ to unlock the next chapter.
The open() function tells the operating system that your program wants to access a specific file. It returns a file object that you can use to read or write data. Without open(), you cannot interact with files on your hard drive.
'w' (write) mode opens a file for writing and erases all existing content first. 'a' (append) mode opens a file for writing but adds new content to the end without deleting anything. Use 'a' when you want to keep the old data.
Closing a file releases the file handle back to the operating system. If you open many files without closing, your program can run out of file handles. Also, for writing, close() ensures your data is actually saved to the disk.
Python raises a FileNotFoundError. The program will stop and show an error message unless you have a try-except block to handle it. Always check that the file exists before opening it in 'r' mode.
Use the .readlines() method on the file object. For example, `lines = f.readlines()` creates a list where each element is one line of the file, including the newline character at the end of each line.
Yes, if you use 'w' or 'a' mode and the file does not exist, Python will create a new empty file first. In 'r' mode, it will not create the file and will raise an error instead.
You've finished Simple File Operations. Continue through the PCEP-30-02 study guide to build a complete picture of the exam.
Done with this chapter?