0

I have a csv file in my custom module that I would like to open and parse in my Setup/InstallData file. The csv is located in MyModule/MyDirectory/files/. When I try to reference the file using the relative path, ../../files/myfile.csv, I get the error:

[ErrorException]
file(../../files/myfile.csv): failed to open stream: No such file or directory

How can I get the file path of my csv so I can open it using open() ?

2

You can try to implement something similar to \Magento\Framework\Module\Dir ->getDir('YourModule', 'files') which is usually called by \Magento\Framework\Module\Dir\Reader ->getModuleDir(DIR_TYPE, 'moduleName').

// inject component registrar
private $componentRegistrar;
public function __construct(\Magento\Framework\Component\ComponentRegistrarInterface $componentRegistrar)
{
    $this->componentRegistrar = $componentRegistrar;
}

// custom getDir method
public function getDir($moduleName, $type = '')
{
    $path = $this->componentRegistrar->getPath(\Magento\Framework\Component\ComponentRegistrar::MODULE, $moduleName);

    if ($type) {
        $path .= '/' . $type;
    }

    return $path;
}

// usage ->getDir('YourModule', 'files')

Update: Note that built-in getDir() method only accepts the following folder types: Dir::MODULE_ETC_DIR = 'etc' Dir::MODULE_ETC_DIR = 'i18n' Dir::MODULE_ETC_DIR = 'view' Dir::MODULE_ETC_DIR = 'Controller' That is why you have to write your own method to reach your 'files' folder.

1
  • Thanks for the reply. I used $importFile = realpath('./') . '/app/code/MyModule/Mydirectory/files/myfile.csv'; but your way looks better :) May 19 '16 at 13:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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