0
0
Pythonprogramming~5 mins

File modes and access types in Python

Choose your learning style9 modes available
Introduction

File modes tell the computer how you want to open a file, like reading or writing. Access types control what you can do with the file once it is open.

When you want to read data from a file, like reading a list of names.
When you want to save new information to a file, like writing a shopping list.
When you want to add more data to the end of an existing file without erasing it.
When you want to update or change parts of a file.
When you want to create a new file if it does not exist.
Syntax
Python
open(filename, mode)

The filename is the name of the file you want to open.

The mode is a string that tells Python how to open the file, like 'r' for read or 'w' for write.

Examples
Open the file data.txt for reading only.
Python
open('data.txt', 'r')
Open the file log.txt to add new data at the end.
Python
open('log.txt', 'a')
Open the file notes.txt for writing. This will erase existing content.
Python
open('notes.txt', 'w')
Create a new file config.txt. It will fail if the file already exists.
Python
open('config.txt', 'x')
Sample Program

This program shows how to open a file in different modes: write, read, and append. It first writes a line, then reads and prints it, then adds another line, and reads again to show the updated content.

Python
filename = 'example.txt'

# Open file for writing (this will create or overwrite the file)
with open(filename, 'w') as file:
    file.write('Hello, world!\n')

# Open file for reading
with open(filename, 'r') as file:
    content = file.read()
    print('Content read from file:')
    print(content)

# Open file for appending
with open(filename, 'a') as file:
    file.write('This is an added line.\n')

# Read again to see the appended content
with open(filename, 'r') as file:
    content = file.read()
    print('Content after appending:')
    print(content)
OutputSuccess
Important Notes

Using with open(...) is best because it automatically closes the file when done.

Opening a file in write mode ('w') erases the file content if it exists.

Append mode ('a') adds new data at the end without deleting existing content.

Summary

File modes control how you open a file: read, write, append, or create.

Choose the mode based on what you want to do with the file.

Always close files or use with to avoid problems.