I have the following code:

protected $_fileSystem;
protected $_directoryList;

public function __construct(
    \Magento\Framework\Filesystem $fileSystem,
    \Magento\Framework\App\Filesystem\DirectoryList $directoryList
) {
    $this->_fileSystem = $fileSystem;
    $this->_directoryList = $directoryList;

public function execute(){

private function writeToCSV(){

        $media = $this->_fileSystem->getDirectoryWrite($this->_directoryList::MEDIA);
        $media->writeFile('text.txt', 'test');
    catch(Exception $e){


However, this doesn't seem to be writing anything to the text file that exists within the same folder as the controller.

1 Answer 1


Try Following way,


protected $filesystem;
protected $directoryList;
protected $csvProcessor;

public function __construct(
    \Magento\Framework\File\Csv $csvProcessor,
    \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
    \Magento\Framework\Filesystem $filesystem
    $this->filesystem = $filesystem;  
    $this->directoryList = $directoryList;
    $this->csvProcessor = $csvProcessor;

function writeToCsv(){
    $fileDirectoryPath = $this->directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR);

        mkdir($fileDirectoryPath, 0777, true);
    $fileName = 'export.csv';
    $filePath =  $fileDirectoryPath . '/' . $fileName;

    $data = [];
      /* pass data array to write in csv file */
    $data[] = ['orderid' => '100001'];
        ->saveData($filePath, $data);

    return true;

You can check your generated CSV file inside var folder

  • I'll give it a whirl. Thanks again Rakesh, always super fast at answering questions. Commented Jan 18, 2019 at 11:32
  • Just a quick question about the directory path. Do I carry on from \Magento\Framework\App\ as though I was in the app folder? So in my case code\company\module? Commented Jan 18, 2019 at 11:38
  • my path is var directory you can set your path Commented Jan 18, 2019 at 11:42
  • @RakeshDonga, How can I collect customer wishlist data and download as a CSV file? Please help me
    – Mohammad
    Commented Dec 29, 2019 at 12:32
  • 1
    @RakeshDonga crystal clear answer.. :) Commented Mar 18, 2020 at 4:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.