File Handling in MEL – Part1

In this tutorial, we will be covering the file handling functionality provided by MEL.
Problem:
Writing out to and reading from file formats other than maya ascii and binary.
Solution:
Write the file location of texture maps used in a scene

 $fileId = `fopen "/home/user/textureList.txt" "w"`;
 $fileNodes = `ls -type "file"`;
 if( size($fileNodes)==0 ) {
 fprint $fileHandle "No File Nodes found in scene";
 }
 else {
 for ($each in `ls -type "file"`) {
 fprint $fileHandle (getAttr ($each + ".fileTextureName") + "n");
 }
 }
 fclose $fileHandle;
 

Read the contents of the written file and print the contents of each line.

 $fileHandle = `fopen "/home/user/textureList.txt" "r"`;
 while (! `feof $fileHandle`) {
 $eachLine = `fgetline $fileHandle`;
 print $eachLine;
 }
 fclose $fileHandle;
 


Commands:

fopen,fprint,fgetline,fclose,getAttr

Discussion:

The first code block writes the file paths of all the texture maps in the scene to a text file names textureList.txt. The fopen command returns a file identifier which can be used to write in to or read from the file specified in the command.An additional string can also be mentioned to denote whether to open the file for read,write or append operation(r ,w or a). Data can be written to the file using fprint command. Its advised to close the file handle once the read, write or append operation is finished. This can be done using the command fclose.

Data can be read by opening the file handle in “r” mode. The fgetline command reads the contents of the file line by line, which is then printed on to the screen.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s