How to write a file programmatically

/**
 * @param string $directory
 * @param string $relativeFileName
 * @param string $contents
 * @return void
 */
function df_file_write($directory, $relativeFileName, $contents) {
	/** @var \Magento\Framework\App\ObjectManager $om */
	$om = \Magento\Framework\App\ObjectManager::getInstance();
	/** @var \Magento\Framework\Filesystem $filesystem */
	$filesystem = $om->get('Magento\Framework\Filesystem');
	/** @var \Magento\Framework\Filesystem\Directory\WriteInterface|\Magento\Framework\Filesystem\Directory\Write $writer */
	$writer = $filesystem->getDirectoryWrite($directory);
	/** @var \Magento\Framework\Filesystem\File\WriteInterface|\Magento\Framework\Filesystem\File\Write $file */
	$file = $writer->openFile($relativeFileName, 'w');
	try {
		$file->lock();
		try {
			$file->write($contents);
		}
		finally {
			$file->unlock();
		}
	}
	finally {
		$file->close();
	}
}

See also other filesystem topics: