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.
File modes and access types in 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.
data.txt for reading only.open('data.txt', 'r')
log.txt to add new data at the end.open('log.txt', 'a')
notes.txt for writing. This will erase existing content.open('notes.txt', 'w')
config.txt. It will fail if the file already exists.open('config.txt', 'x')
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.
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)
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.
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.