How to write text file and create directory in Magento 2 standard way?

You can write the content dynamically in text(.txt) file using Programmatic way with Magento 2 Standard approach.

Sometimes you need to create a directory and write a text file in the specific location of the system, You can add the content with interface Magento\Framework\Filesystem\Directory\WriteInterface.

I will show you to demo for writing the text file at a var folder with a custom folder. Let’s think our file is stored under the var/custom/demo.txt file in the Magento root. You need to create a Model class with a user-defined function to create a custom directory and demo text file.

namespace Jesadiya\TextFile\Model;

use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Filesystem\Directory\WriteInterface;

class WriteTextFile
     * @var DirectoryList
    private $directoryList;

     * @var Filesystem
    private $filesystem;

    public function __construct(
        DirectoryList $directoryList,
        Filesystem $filesystem
    ) {
        $this->directoryList = $directoryList;
        $this->filesystem = $filesystem;

     * create custom folder and write text file
     * @return bool
    public function createDemoTextFile()
        $varDirectory = $this->filesystem->getDirectoryWrite(
        $varPath = $this->directoryList->getPath('var');
        $fileName = 'demo.txt'; //textfile name
        $path = $varPath . '/custom/' . $fileName;

        // Write Content
        $this->write($varDirectory, $path);

     * Write content to text file
     * @param WriteInterface $writeDirectory
     * @param $filePath
     * @return bool
     * @throws FileSystemException
    public function write(WriteInterface $writeDirectory, string $filePath)
        $stream = $writeDirectory->openFile($filePath, 'w+');
        $fileData = 'Last Imported Order Id: 10000001';

        return true;

This scenario is used when you have integrated Third-party tools for the order import/export and you can synchronization the last order send to the Third-party tools.

You can track the order id, with write down the latest order id to a text file, which was last successfully imported to the Third-party platform.