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.

with open('C:/myfile.ma', 'r') as fh:
    lines = fh.readlines()

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

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))
comments powered by Disqus