- Open files with
open()and choose the correct file mode. - Write, append and read text files.
- Use the
withstatement 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():
| Mode | Purpose | If file does not exist | Existing content |
|---|---|---|---|
r | Read only (default mode). | FileNotFoundError | Kept |
w | Write only. | Creates a new file | Erased (file emptied first) |
a | Append – write at the end. | Creates a new file | Kept; new data added at the end |
x | Exclusive create – write to a new file. | Creates a new file | FileExistsError if it exists |
r+ | Read and write. | FileNotFoundError | Kept – writing starts at the beginning and overwrites characters at that position |
w+ | Write and read. | Creates a new file | Erased |
a+ | Append and read. | Creates a new file | Kept; 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
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())Line 1: Python Line 2: Files Line 3: Append Line 4: Done
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())alpha ['beta\n', 'gamma\n'] 1 alpha 2 beta 3 gamma
| Method | Returns |
|---|---|
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 callf.close()yourself.- Handle missing files with
FileNotFoundError; check existence withos.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"))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.
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
wandw+erase a file;aanda+add to the end;randr+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)
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.
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.
- Python Software Foundation. (n.d.). Input and Output. In The Python Tutorial. https://docs.python.org/3/tutorial/inputoutput.html
- Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
- Python Software Foundation. (n.d.). os — Miscellaneous operating system interfaces. The Python Standard Library. https://docs.python.org/3/library/os.html
- van Rossum, G., & Coghlan, N. (2005). PEP 343 – The “with” Statement. Python Enhancement Proposals. https://peps.python.org/pep-0343/
- Python Software Foundation. (n.d.). Errors and Exceptions. In The Python Tutorial. https://docs.python.org/3/tutorial/errors.html
- Google Colaboratory. (n.d.). External data: Local Files, Drive, Sheets, and Cloud Storage (example notebook). https://colab.research.google.com/notebooks/io.ipynb
- Google. (n.d.). Google Colaboratory – Frequently Asked Questions. https://research.google.com/colaboratory/faq.html