Files and Paths

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

output = open('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
lines = 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.

maya_file = open('C:/myfile.ma', 'r')
lines = maya_file.readlines()
maya_file.close()
# Use a list comprehension to generate a list of items in one go
lines = [line.replace('myBadSphere', 'myGoodSphere') for line in lines]
maya_file = open('C:/myfile2.ma', 'w')     
maya_file.writelines(lines)             
maya_file.close()

Python also makes it easy to find files and traverse directory hierarchies.

# Get all the Maya files in a directory
import os
maya_files = []
for content in os.listdir('C:/somedirectory'):
    if content.endswith('.ma') or content.endswith('.mb'):
        maya_files.append(content)

# Traverse a directory and all subdirectories for fbx files
fbx_files = []
for root, dirs, files in os.walk('/my/tools/directory'):
    print('Currently searching {0}'.format(root))
    for file_name in files:
        if file_name.endswith('.fbx'):
            fbx_files.append(os.path.join(root, file_name))

4 thoughts on “Files and Paths”

Nando December 11, 2015 at 11:21 am

These are really helpful instructions! Thank you so much

Sometimes there is r in front of the open location
(r’C:\myfile.ma’, ‘w’)
What does it stands for?

Chad January 5, 2016 at 7:41 pm

The r is a raw string. It is used when you don’t want to escape the backslashes in the string.

pablo June 22, 2016 at 2:07 pm

#Hello Chad I tried to export a FBX file in a especific directory
for aux in jon:
cmds.file(aux, options= “v=0”, type= “FBX export”, preserveReferences=True, exportSelected=True)
#I dont know were puth the path like
cmds.file(“C:/Users/clear.fbx”)

Chad June 25, 2016 at 9:57 pm

Hi Pablo,
Your command looks correct. The path should be the first argument. Make sure the directory exists before you export the file.

Leave A Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

<code> For inline code.
[sourcecode] For multiline code.