Tutorial: Using the WP_Filesystem
Writing files from code, whether it be from a theme or from a plugin, is generally bad mojo. However understanding why you shouldn’t is confusing to many, and then understanding why you shouldn’t do-it-yourself and should use the WP_Filesystem is even more confusing.
A great writeup by Otto on how, why, and when to use WP_Filesystem to write files from a WordPress theme or plugin, including code samples and a demo plugin.