Read a file in read mode

EasyFile Handling Programs · 1 of 38

Write a Python program to read a file in reading mode.

Advertisement
Output
Python file handling
is easy with open()

Approach

  1. Create a sample file, then open it with mode “r” inside a with block and read it.

Solution

Python
with open("notes.txt", "w") as f:    f.write("Python file handling\nis easy with open()\n") with open("notes.txt", "r") as f:    content = f.read()print(content)
Output
Python file handling
is easy with open()

Line by line

Lines 1-2

Creates the sample file so the program runs anywhere.

Line 4

Mode “r” (the default) opens the file for reading; with closes it automatically.

Line 5

read() returns the whole file as one string.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More file handling programs

← All 38 File Handling Programs