1. Opening a File

Python uses the built-in open()
function:
# Syntax: open(filename, mode)
file = open("example.txt", "r")
File Modes
Mode | Description |
---|---|
"r" | Read (default) – opens file for reading; error if file doesn’t exist |
"w" | Write – creates file or overwrites existing file |
"a" | Append – creates file if not exists, adds content at the end |
"x" | Create – creates file; error if file exists |
"b" | Binary mode (e.g., "rb" , "wb" ) |
"t" | Text mode (default, e.g., "rt" ) |
2. Reading from a File
file = open("example.txt", "r")
content = file.read() # Reads entire file
print(content)
file.close()
Other methods:
file.readline() # Reads one line
file.readlines() # Reads all lines as a list
3. Writing to a File
file = open("example.txt", "w")
file.write("Hello, Python!\n")
file.write("This is file handling.\n")
file.close()
- If
"w"
is used, the old content is erased. - Use
"a"
mode to append instead:
file = open("example.txt", "a")
file.write("Adding new line without erasing old content.\n")
file.close()
4. Using with
Statement
It is recommended to use with
to avoid forgetting close()
:
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
- Automatically closes the file after block execution.
5. Handling Errors in File Operations
Often combined with exception handling:
try:
with open("data.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found!")
Summary
- Use
open(filename, mode)
to work with files. "r"
,"w"
,"a"
,"x"
,"b"
, and"t"
are common file modes.- Always close files after use, or better use
with
. - Combine file handling with exception handling for safer code.