0
0
Pythonprogramming~5 mins

Reading file data in Python

Choose your learning style9 modes available
Introduction

Reading file data lets your program get information stored in files. This helps your program use or show data saved earlier.

You want to load a list of names saved in a text file.
You need to read settings from a file to configure your app.
You want to process a log file to find errors.
You want to read a saved message or note from a file.
Syntax
Python
with open('filename.txt', 'r') as file:
    data = file.read()

open() opens the file. 'r' means read mode.

with makes sure the file closes automatically after reading.

Examples
This reads the whole file content as one string.
Python
with open('example.txt', 'r') as file:
    content = file.read()
This reads the file line by line into a list of strings.
Python
with open('example.txt', 'r') as file:
    lines = file.readlines()
This also reads the whole file but you must close the file yourself.
Python
file = open('example.txt', 'r')
content = file.read()
file.close()
Sample Program

This program first writes two lines to a file, then reads and prints them.

Python
with open('sample.txt', 'w') as f:
    f.write('Hello\nWorld!')

with open('sample.txt', 'r') as f:
    data = f.read()

print(data)
OutputSuccess
Important Notes

Always use with to open files to avoid forgetting to close them.

Reading large files with read() can use a lot of memory; consider reading line by line.

Summary

Use open() with mode 'r' to read files.

with helps manage file closing automatically.

You can read whole files or line by line depending on your need.