SyntaxStudy
Sign Up
Home Python Reference open() / with statement

open() / with statement

function

Opens a file and returns a file object. Always use with statement to ensure the file is properly closed.

Syntax

open(file, mode='r', encoding=None)

Example

python
# Read file
with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()
    lines   = f.readlines()

# Write file
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, World!\n')

# Append
with open('log.txt', 'a') as f:
    f.write('New log entry\n')