By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
Reading and writing text files is a fundamental skill in Python programming. It allows you to interact with external data, save program outputs, and load configurations. This topic is crucial for data processing, logging, and configuration management. Incorrect file handling can lead to data loss, corruption, or security vulnerabilities. For instance, opening a file in write mode (w) will overwrite existing content, potentially losing important data.
w
r
a
r+
open()
open('filename', 'mode')
file = open('example.txt', 'r')
⚠️ Pitfall: Forgetting to close the file can lead to resource leaks.
Use the with statement:
with
with open('filename', 'mode') as file:
python with open('example.txt', 'r') as file: content = file.read()
⚠️ Pitfall: Not using with can lead to unclosed files.
Read from a file:
file.read()
file.readline()
file.readlines()
read()
readline()
readlines()
⚠️ Pitfall: Reading large files with read() can consume excessive memory.
Write to a file:
file.write('text')
python with open('example.txt', 'w') as file: file.write('Hello, World!')
⚠️ Pitfall: Writing in w mode will overwrite existing content.
Append to a file:
python with open('example.txt', 'a') as file: file.write('Appending text.')
⚠️ Pitfall: Forgetting to use a mode can overwrite the file.
Read and write using r+ mode:
python with open('example.txt', 'r+') as file: content = file.read() file.write('Adding more text.')
Experts view file handling as a managed resource operation. They prioritize using the with statement to automatically handle file closing, reducing the risk of resource leaks. They also consider the file mode carefully to avoid unintended data loss or corruption.
Exam trap: Questions that omit file closing.
The mistake: Using w mode when intending to append.
Exam trap: Questions that require appending data.
The mistake: Reading large files with read().
Exam trap: Scenarios involving large file handling.
The mistake: Writing without seeking in r+ mode.
file.seek()
Exam trap: Questions that involve both reading and writing.
The mistake: Not handling file not found errors.
python with open('config.txt', 'r') as file: content = file.read() print(content)
Why it works: with statement manages file closing, read() reads the entire file.
Scenario: You need to append a log entry to a log file.
python with open('log.txt', 'a') as file: file.write('New log entry.\n')
Why it works: a mode appends text to the end of the file.
Scenario: You need to read a large file line by line and process each line.
python with open('largefile.txt', 'r') as file: for line in file: process(line)
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.