MEL How-To #40

Back · Previous · Next Maya

How do I extract just the filename or just the directory from an absolute path description?

Using the example path:

string $fullpath = "c:/maya/projects/default/sourceimages/myImage.tif"

I use a few handy dandy utility procedures to deal with filepaths, filenames and the different slashes used for Windows vs. UNIX/Maya.

The ‘filepart’ script extracts just the filename from the path description:

global proc string filepart( string $path )
// Extracts the path portion of an absolute filepath.
// Input: e.g. "D:/projects/default/scenes/myScene.mb"
// Result: e.g. "myScene.mb"
//
// Filepath can be delimited with
// either slash ("/" or "\")
{
  string $filepart = match( "[^/\\]*$", $path );

  return $filepart;
}

The ‘pathpart’ script extracts just the directory from the path description:

proc string pathpart( string $path )
// Extracts the path portion of an absolute filepath.
// Input: e.g. "D:/projects/default/scenes/myScene.mb"
// Result: e.g. "D:/projects/default/scenes"
//
// Note: Requires that the filepath be delimited with
//       _forward_ slashes ("/")
{
  string $dir = match( "^.*/", $path );

  int $sz = size( $dir );
  // Strip off trailing '/'
  //
  if ( ( $sz > 1 ) && ( substring( $dir, $sz, $sz ) == "/" ) ) {
    $dir = substring( $dir, 1, ($sz - 1) );
  }
  return $dir;

}

So, to get just the filename from the path description:

string $file = filepart( $fullpath );
// Result: myImage.tif //

And, to get just the directory from the path description:

string $directory = pathpart( $fullpath );
// Result: c:/maya/projects/default/sourceimages //

Related How-To's

Thursday, September 07, 2000