0
0
Pythonprogramming~5 mins

Opening and closing files in Python

Choose your learning style9 modes available
Introduction

We open files to read or write data. Closing files saves changes and frees resources.

When you want to read data from a text file like a list of names.
When you want to save user input into a file for later use.
When you need to update or add information to an existing file.
When you want to process data stored in a file, like logs or reports.
Syntax
Python
file = open('filename.txt', 'mode')
# work with the file
file.close()

'mode' can be 'r' for reading, 'w' for writing, or 'a' for appending.

Always close the file to save changes and avoid errors.

Examples
Open a file to read all its content, then close it.
Python
file = open('data.txt', 'r')
content = file.read()
file.close()
Open a file to write text, overwriting existing content, then close it.
Python
file = open('log.txt', 'w')
file.write('Hello world!')
file.close()
Open a file to add text at the end without deleting existing content, then close it.
Python
file = open('notes.txt', 'a')
file.write('\nNew line added.')
file.close()
Sample Program

This program writes a sentence to a file, closes it, then reopens to read and print the content.

Python
file = open('example.txt', 'w')
file.write('This is a test file.')
file.close()

file = open('example.txt', 'r')
content = file.read()
file.close()

print(content)
OutputSuccess
Important Notes

Using with open('filename', 'mode') as file: automatically closes the file.

Forgetting to close files can cause data loss or errors.

Summary

Open files to read or write data.

Always close files after finishing to save and free resources.

Use modes like 'r', 'w', and 'a' to control how you access the file.