Learning Objectives – after this chapter you will be able to:
  • Open files with open() and choose the correct file mode.
  • Write, append and read text files.
  • Use the with statement so files are always closed.
  • Mount Google Drive in Colab and read/write files stored there.
Files in Python
  • Variables lose their values when a program ends. Files store data permanently on disk.
  • Working with a file has three steps: open → read / write → close.
  • open(file, mode) returns a file object. Text files are read and written as strings; binary files (images, PDFs) as bytes.
File System MODES

The following modes are supported by open():

ModePurposeIf file does not existExisting content
rRead only (default mode).FileNotFoundErrorKept
wWrite only.Creates a new fileErased (file emptied first)
aAppend – write at the end.Creates a new fileKept; new data added at the end
xExclusive create – write to a new file.Creates a new fileFileExistsError if it exists
r+Read and write.FileNotFoundErrorKept – writing starts at the beginning and overwrites characters at that position
w+Write and read.Creates a new fileErased
a+Append and read.Creates a new fileKept; writes always go to the end

Add b for binary files, e.g. "rb" or "wb". For text files it is good practice to state the encoding: open("a.txt", "w", encoding="utf-8").

Writing, Appending and Reading
write() and writelines() add text; read() returns the whole file
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Line 1: Python\n")
    f.write("Line 2: Files\n")

with open("notes.txt", "a", encoding="utf-8") as f:
    f.writelines(["Line 3: Append\n", "Line 4: Done\n"])

with open("notes.txt", "r", encoding="utf-8") as f:
    print(f.read())
Output
Line 1: Python
Line 2: Files
Line 3: Append
Line 4: Done
readline(), readlines() and looping over a file
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("alpha\nbeta\ngamma\n")

with open("notes.txt", encoding="utf-8") as f:
    print(f.readline().strip())     # one line
    print(f.readlines())            # remaining lines as a list

with open("notes.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):   # line by line (memory-efficient)
        print(number, line.strip())
Output
alpha
['beta\n', 'gamma\n']
1 alpha
2 beta
3 gamma
MethodReturns
read()The whole file as one string (read(n) reads n characters).
readline()The next line, including its \n.
readlines()A list of all remaining lines.
write(s)Writes string s and returns the number of characters written.
tell() / seek(pos)Current position / move to a position.
The with Statement and Error Handling
  • with open(...) as f: automatically closes the file when the block ends – even if an error occurs. Without it you must call f.close() yourself.
  • Handle missing files with FileNotFoundError; check existence with os.path.exists().
import os

with open("data.txt", "w") as f:
    f.write("hello")
print(f.closed)                 # closed automatically

try:
    with open("missing.txt") as f:
        print(f.read())
except FileNotFoundError:
    print("missing.txt does not exist")

print(os.path.exists("data.txt"), os.path.getsize("data.txt"))
os.remove("data.txt")
print(os.path.exists("data.txt"))
Output
True
missing.txt does not exist
True 5
False
Using Google Drive in Colab
  • Files created in Colab are stored on a temporary virtual machine and are deleted when the runtime ends.
  • To keep files permanently, mount Google Drive. Colab asks you to sign in and allow access; your Drive then appears at /content/drive/MyDrive.
Mount Drive and write a file (works only inside Google Colab)
from google.colab import drive
drive.mount('/content/drive')          # follow the sign-in prompt

path = "/content/drive/MyDrive/python_notes.txt"
with open(path, "w", encoding="utf-8") as f:
    f.write("Saved permanently in Google Drive\n")

with open(path, encoding="utf-8") as f:
    print(f.read())

You can also upload files from your computer with the Files panel (folder icon on the left) or with from google.colab import files; files.upload().

Key Takeaways
  • w and w+ erase a file; a and a+ add to the end; r and r+ need an existing file.
  • Always prefer with open(...) – it closes the file automatically.
  • In Colab, mount Google Drive to keep files after the runtime ends.
Video : File System and Google Drive
Question / Answer (15 questions)

Answer : Variables are stored in memory and are lost when the program ends. Files store data permanently on disk so it can be reused later or shared with other programs.

Answer : Open the file with open(), read from or write to it using the file object’s methods, and close it with close() – or use a with statement, which closes it automatically.

Answer : w opens a file for writing and erases any existing content (creating the file if needed). a opens a file for appending: existing content is kept and new data is written at the end.

Answer : Both allow reading and writing. r+ requires the file to exist and keeps its content, with writing starting at the beginning and overwriting characters there. w+ creates the file if needed and erases existing content first.

Answer : x (exclusive creation) creates a new file for writing and raises FileExistsError if the file already exists, preventing accidental overwriting.

Answer : Python raises FileNotFoundError. It can be handled with try-except or avoided by checking os.path.exists() first.

Answer : read() returns the entire file (or n characters) as one string. readline() returns the next single line including its newline. readlines() returns a list containing all remaining lines.

Answer : for line in f reads one line at a time, so the whole file is never loaded into memory at once, unlike read() or readlines().

Answer : with acts as a context manager: the file is automatically closed when the block ends, even if an exception occurs, preventing resource leaks and lost data.

Answer : write(s) returns the number of characters written. It does not add a newline automatically – include "\n" yourself.

Answer : The default encoding depends on the operating system. Stating UTF-8 makes the program read and write non-English characters consistently on every computer.

Answer : tell() returns the current position in the file. seek(pos) moves the position, for example seek(0) returns to the beginning so the file can be read again.

Answer : Add b to the mode, for example open("photo.jpg", "rb") to read or "wb" to write. Data is then handled as bytes instead of strings.

Answer : Colab runs on a temporary virtual machine whose storage is deleted when the runtime ends. Mounting Google Drive with drive.mount("/content/drive") and saving under /content/drive/MyDrive keeps files permanently.

Answer : from google.colab import drive, then drive.mount('/content/drive'). After granting permission, Drive files are available under /content/drive/MyDrive.
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. Which mode erases existing content before writing?

Show Answer

Correct Answer : D. w
w truncates the file to zero length first.

Q2. Which is the default mode of open()?

Show Answer

Correct Answer : A. r
If no mode is given, the file is opened for reading in text mode.

Q3. Which method returns a LIST of lines?

Show Answer

Correct Answer : C. readlines()
readlines() returns all remaining lines as a list.

Q4. Opening an existing file in x mode raises:

Show Answer

Correct Answer : B. FileExistsError
x is exclusive creation and fails if the file already exists.

Q5. In Colab, Google Drive files appear under which path after mounting at /content/drive?

Show Answer

Correct Answer : A. /content/drive/MyDrive
The user’s Drive is available at /content/drive/MyDrive.

Bibliography/References

The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.

  1. Python Software Foundation. (n.d.). Input and Output. In The Python Tutorial. https://docs.python.org/3/tutorial/inputoutput.html
  2. Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
  3. Python Software Foundation. (n.d.). os — Miscellaneous operating system interfaces. The Python Standard Library. https://docs.python.org/3/library/os.html
  4. van Rossum, G., & Coghlan, N. (2005). PEP 343 – The “with” Statement. Python Enhancement Proposals. https://peps.python.org/pep-0343/
  5. Python Software Foundation. (n.d.). Errors and Exceptions. In The Python Tutorial. https://docs.python.org/3/tutorial/errors.html
  6. Google Colaboratory. (n.d.). External data: Local Files, Drive, Sheets, and Cloud Storage (example notebook). https://colab.research.google.com/notebooks/io.ipynb
  7. Google. (n.d.). Google Colaboratory – Frequently Asked Questions. https://research.google.com/colaboratory/faq.html