• Home
  • Reel/Resume
  • Work
  • Downloads
  • Resources
  • About
  • Contact
Home » Resources » Python Scripting for Maya Artists » File Input and Output

File Input and Output

Python is used a lot in managing files and file systems.

>>> output = open(r'X:\data.dat', 'w')  # Open file for writing
>>> input = open('data.txt', 'r')       # Open file for reading
>>> x = input.read()                    # Read entire file
>>> x = input.read(5)                   # Read 5 bytes
>>> x = input.readline()                # Read next line
>>> L = input.readlines()               # Read entire file into a list of line strings
>>> output.write(“Some text”)           # Write text to file
>>> output.writelines(list)             # Write all strings in list L to file
>>> output.close()                      # Close manually

Here’s a more practical example of opening a maya ascii file and renaming myBadSphere to myGoodSphere.

>>> mayaFile = open(r'C:\myfile.ma', 'r')
>>> fileContents = mayaFile.readlines()
>>> mayaFile.close()
>>> for i in range(len(fileContents)):
>>>     fileContents[i] = fileContents[i].replace('myBadSphere', 'myGoodSphere')
>>> mayaFile = open(r'C:\myfile2.ma', 'w')
>>> mayaFile.writelines(fileContents)
>>> mayaFile.close()

Home » Resources » Python Scripting for Maya Artists » File Input and Output

© 2009 Chad Vernon