File Handling
Writing Files
write, writelines, and file output patterns
Interview: File output — tests understanding of write modes, buffering, and efficient output
Writing files in Python uses write() and writelines() methods. Understanding the difference between write mode ('w', overwrites) and append mode ('a', adds to end) is critical to avoid data loss.
Writing Methods
f.write(string): Write a string, returns number of characters writtenf.writelines(list): Write a list of strings (no separators added)print(..., file=f): Use print function to write to filef.flush(): Force write buffer to disk immediately
Common Pitfall
writelines() does NOT add newlines between lines. You must include them: f.writelines([line + '\n' for line in lines]).
Use Cases
Writing log files for application monitoring
Generating reports and output files
Saving application state and configuration
Creating data export files (CSV, JSON)
Template-based file generation
Common Mistakes
Using write mode ('w') when you meant append ('a') — overwrites existing data!
Forgetting that writelines() doesn't add newlines between items
Not specifying encoding for text files
Not flushing or closing before reading the file back
Writing binary data in text mode (use 'wb' for bytes)