Python Practice › File Handling Programs › Program 1
Read a file in read mode
Write a Python program to read a file in reading mode.
Output
Python file handling is easy with open()
Approach
- Create a sample file, then open it with mode “r” inside a
withblock and read it.
Solution
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.
Learn the concept
New to this topic? Read the lesson, then come back.