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 =                   # Read entire file
x =                  # 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:/', 'r')
lines = maya_file.readlines()
# 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:/', 'w')     

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'):

# 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:\’, ‘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

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.