How to Read and Write Files in Python

In this example, we will learn how to conduct simple read and write files in Python.

2. Functions

Below list python built-in functions related to the work.

  • open(): open a file and create a file object.
  • write(): write the contents to file.
  • read(): read all the content.
  • readline(): read line by line.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# Create a text file test.txt
with open("test.txt", "wt") as out_file:
    out_file.write("Happy Christmas!")

# Read a file
with open("test.txt", "rt") as in_file:
    text =

# print this text
Happy Christmas!
Notify of
Inline Feedbacks
View all comments