Wednesday, December 8, 2010

MEL Scripting Tutorial: How To Write To A Text File

In this mel scripting tutorial we'll look at how to write data out to a file so you can make your own data exporting tools. By the end of it you'll have a firm understanding of and know how to take data from your Maya scene and write it out to a file. This is a follow up to the previous tutorial: How To Read A Text File. This article assumes you've read the previous tutorial and is a continuation of the concepts discussed in it. If you've not read the tutorial on how to read a text file, please browse Script Swell's Technical Artist Tutorials or click here.

Skill Level: Beginner to Intermediate

There are two things you'll need in order to proceed: some data to write out, and a text a file to write it to. To start off let's create a string array in Maya. In the script editor, copy and paste the following and run it.
// Create A String Array With Test Data
string $myStrArray[] = {"This is line one of my data from Maya.", "This is line two.", "And then line three!"} ;
Next, create a file in an easy location, e.g. "C:\mel\testFile_v01.txt". In this file, on the first line type the following: "This is the first line of my text file, version 01!". Save and close your file.

Now let's get into some code and see how this works. The idea here is that we're going to "open" our file as an object in Maya, put our data inside it, then "close" it. If you recall in the previous tutorial we use the fopen command to open the file and prepare it for use.
// Create A String Array With Test Data
string $myStrArray[] = {"This is line one of my data from Maya.", "This is line two.", "And then line three!"} ;

// Define Your File Path
string $filePath = "C:/mel/testFile_v01.txt" ;

// Open Your File
$fileId = `fopen $filePath "a"` ;
The first difference you may have noticed from the previous tutorial is that instead of "r" (for 'read') we've switched to "a" which stands for "append". What this means is that we're telling MEL that when we're working with this particular file, we'll be writing to it but we'll be appending data onto the end of whatever is there. This way using the "a" flag you can keep your current data intact and simply add more to it. Let's continue on with more code.
// Create A String Array With Test Data
string $myStrArray[] = {"This is line one of my data from Maya.", "This is line two.", "And then line three!"} ;

// Define Your File Path
string $filePath = "C:/mel/testFile_v01.txt" ;

// Open Your File
$fileId = `fopen $filePath "a"` ;

// Print Array To File
for($line in $myStrArray)
fprint $fileId ($line+"\n") ;

// Close File
fclose $fileId ;
The newest line in our code starts with a for in loop and is looping through our string array one line at a time. This is because in this case we don't just want to dump all the data to the file, we want to have control over how it's added and make sure it's exporting to an easily readable format. We loop through our array one line at a time and use the fprint command. What fprint does is essentially the same thing that the normal print command does except it prints to your text file instead of Maya's script editor. Just like print though, it will not add a new line at the end of the argument and this must be done manually, hence the "\n" that I've appended to the $line variable. If you leave this out, all of your data will print to a single line! After we're finished printing out the data we're using fclose to "close" our file object.

-----------------------------------------------------------
Tip: If you forget to use fclose and leave the file object "open" within Maya it will become locked and you won't be able to make changes to it outside of the program. If this happens you will need to close Maya to "unlock" your file.
-----------------------------------------------------------

After running this script, take a look at your text file and you'll see the file now reads the following:
This is the first line of my text file, version 01!
This is line one of my data from Maya.
This is line two.
And then line three!
Nicely done! You are now one step closer to building your data export tool. Next we'll double back slightly and look at another flag we can use in the fopen command. Look at the code below.
// Create A String Array With Test Data
string $myStrArray[] = {"This is line one of my data from Maya.", "This is line two.", "And then line three!"} ;

// Define Your File Path
string $filePath = "C:/mel/testFile_v01.txt" ;

// Open Your File
$fileId = `fopen $filePath "w"` ;

// Print Array To File
for($line in $myStrArray)
fprint $fileId ($line+"\n") ;

// Close File
fclose $fileId ;
The only change here is we've swapped the "a" flag with it's brother: "w" which stands for "write". What write will do is destroy the prior contents of the file and replace them with whatever we're printing to it. So your result will be:
This is line one of my data from Maya.
This is line two.
And then line three!
This time only the string array has been printed to the file and the original file's contents were destroyed.

Both of these flags are useful depending on the context of what you're doing. Be sure to check out these commands in the MEL documentation as well for a slightly more in-depth look at how they work.

It really is simple as that to write out data! As long as you remember to fclose your file and use the correct flags when using fopen you shouldn't have any trouble using this technique.

For more tutorials check out the Technical Artist Tutorials page. Leave a comment below if you have any thoughts or questions and thanks for reading!

Scripting Topics

MEL (41) Maya (39) Scripting (32) Scripts (21) programming (14) Free Mel Scripts (8) MaxScript (7) Coding (6) Rigging (5) tutorial (5) 3ds Max (4) Python (4) Tricks (4) faceware (4) image metrics (4) Learn (3) Namespace (3) Namespacing (3) animation (3) facial (3) webinar (3) Code (2) GDC (2) Game Developers Conference (2) Multiple Namespaces (2) Print Selected Objects (2) Recursive (2) Removing Namespace (2) Return (2) Set Driven Keys (2) TOkenize (2) Tips (2) Toggle Background Color with MEL (2) animation tools (2) animators resource (2) deformers (2) learning (2) maya tools (2) mesh (2) modeling (2) nodes (2) procedure (2) script swell (2) transforms (2) Animschool (1) Attribute (1) Background Color (1) Beer (1) Blur (1) Character Setup (1) Check if an object exists (1) Class (1) Command Line (1) Constraints (1) Create SDK (1) Create a directory with mel (1) Data (1) Export (1) FilterString (1) Fix (1) Floating Slider Time (1) Functions (1) Get Maya Version MEL (1) Get Parent (1) Google (1) Holiday (1) How To Write To A Text File (1) Import (1) Incremental Save (1) Index (1) Joint Chain (1) Make Set Driven Keys (1) Maya Version (1) Modules (1) Objects (1) Orient Constraint (1) PYMEL (1) Parent (1) Parent Constraint (1) Point Constraint (1) Position (1) Print (1) Print Current Selection (1) Print Random Quotes (1) Print Selection (1) Print Vertices (1) Progress Bar (1) Progress Window (1) PyQT (1) Removing Spaces From Names (1) Scene File Name (1) Select Connections (1) Select Outgoing Nodes (1) Split Bones (1) Split Joints (1) St. Patrick's Day (1) String Array (1) System (1) Transfer UVs (1) Viewport (1) White Space (1) Windows Username (1) Zero Out Attributes (1) animButtonState (1) arrays (1) articles (1) auto key (1) better (1) blendshapes (1) break (1) confirm dialog (1) continue (1) convention (1) e3 (1) efficiency (1) error (1) eval (1) executable (1) fclose (1) fopen (1) fprint (1) games (1) improving (1) infinite loop (1) joints (1) listHistory (1) listRelatives (1) logic (1) loops (1) milestone (1) nodeType (1) objExists (1) recursion (1) rotates (1) rotations (1) schools (1) sculpting (1) setAttr (1) shout outs (1) source (1) source a script with a variable (1) speed (1) tech-artists.org (1) translates (1) video (1) warning (1) world matrix (1) worldMatrix (1)
 
Script Swell - Blogged