Python open()
Function
The open() function in Python is used to open files and return a file object. This is the starting point for reading from or writing to a file.
Syntax
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Common Parameters:
file
: Path to the file (required)mode
: Mode to open the file in (default is'r'
)encoding
: For text files, like'utf-8'
File Modes
Mode | Description |
---|---|
'r' | Read (default) – file must exist |
'w' | Write – creates or overwrites file |
'a' | Append – adds to file, creates if needed |
'x' | Create – fails if file exists |
'b' | Binary mode (e.g., 'rb' , 'wb' ) |
't' | Text mode (default) |
'+' | Update mode (read & write) |
Example 1: Reading a File
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
The contents of example.txt
Example 2: Writing to a File
file = open("output.txt", "w")
file.write("Hello, world!")
file.close()
Creates a file with "Hello, world!"
Example 3: Using with
Statement (Best Practice)
with open("data.txt", "r") as f:
print(f.read())
Why use with
? It automatically closes the file after use, even if an error occurs.
Example 4: Reading Line by Line
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
Common Errors
FileNotFoundError
– when opening a non-existent file in read modePermissionError
– when writing to a file you don’t have access to
Use Cases
- Reading configuration files
- Logging messages to a log file
- Processing CSV or text data
Interview Tip
Always use the with open(...)
pattern to handle files safely in coding interviews.
Summary
open()
is used to read/write/create files- Different modes like
'r'
,'w'
,'a'
change behavior - Use
with
to manage files safely
Practice Problem
Write a Python script to copy the contents of one file into another file:
with open("source.txt", "r") as source:
with open("destination.txt", "w") as dest:
dest.write(source.read())