Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. open()

open()

A built-in function for opening files to read and write data. Using it with the with statement automates the file closing process.

Syntax

# Opens a file and returns a file object.
open(file_path, mode='r', encoding=None)

# Using a with statement opens the file and automatically closes it when the block ends.
with open(file_path, mode, encoding=encoding) as f:
    # File operations
    content = f.read()

# Mode options
# 'r'  Read (default)
# 'w'  Write (overwrites the file)
# 'a'  Append (adds to the end of the file)
# 'rb' Binary read
# 'wb' Binary write

Function List

Function / MethodDescription
open(path, mode, encoding)Opens a file and returns a file object. Specify the encoding as 'utf-8' or similar.
f.read(size=-1)Reads the file contents as a string. If size is omitted, the entire file is read.
f.readline()Reads and returns one line from the file. Returns an empty string at the end of the file.
f.readlines()Returns all lines in the file as a list of strings. Each line includes its trailing newline character.
f.write(string)Writes a string to the file. Returns the number of characters written.
f.writelines(lines)Writes a list of strings to the file. Newline characters are not added automatically.
f.close()Closes the file. Not needed when using the with statement.

Sample Code

# Write to a file using a with statement ('w' mode overwrites).
with open("greeting.txt", "w", encoding="utf-8") as f:
    f.write("Hello!\n")
    f.write("Written to a file with Python.\n")
# The file is automatically closed when the with block ends.

# Read a file using a with statement.
with open("greeting.txt", "r", encoding="utf-8") as f:
    content = f.read()  # Reads the entire file as a string.
    print(content)

# Reading line by line processes even large files with low memory usage.
with open("greeting.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line, end="")  # Each line already includes a trailing newline.

# Read line by line manually using readline().
with open("greeting.txt", "r", encoding="utf-8") as f:
    first_line = f.readline()
    print(f"Line 1: {first_line.strip()}")

# Get all lines as a list using readlines().
with open("greeting.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    print(f"Line count: {len(lines)}")

# Append to a file using 'a' mode.
with open("greeting.txt", "a", encoding="utf-8") as f:
    f.write("This line was appended.\n")

# Write multiple lines from a list.
lines_to_write = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w", encoding="utf-8") as f:
    f.writelines(lines_to_write)

# Example of processing a CSV file.
import csv

# Write a CSV file.
data = [["Name", "Score"], ["Taro", 85], ["Hanako", 92]]
with open("scores.csv", "w", encoding="utf-8", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(data)

# Read a CSV file.
with open("scores.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Notes

When working with files, always use the with statement. If you call open() without a with statement, an exception could leave the file unclosed, causing a resource leak. The with statement automatically calls close() when the block exits, even if an exception occurs.

It is strongly recommended to specify the encoding explicitly when working with text files. If you omit encoding="utf-8", Python uses the system's default encoding (such as Shift_JIS on Windows), which can cause garbled text.

When reading large files, avoid loading the entire file into memory at once with read(). Instead, iterate over the file object directly with for line in f: to process the file with minimal memory usage. For the basics of how iterators work, see callable() / iter() / next().

If you find any errors or copyright issues, please .