Book Image

Practical Maya Programming with Python

By : Robert Galanakis
Book Image

Practical Maya Programming with Python

By: Robert Galanakis

Overview of this book

Table of Contents (17 chapters)
Practical Maya Programming with Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Path building and manipulation


You will often have to construct file system paths using Python. For example, given the variable mydir which points to some path, you may want to get the path two folders up:

otherdir = mydir + '\\..\\..'

Do not build or manipulate paths this way. There are a number of things wrong with this code. The obvious problem is that it is platform-dependent. Windows and Linux-based systems use different path separators.

Even more importantly, this code (and code that uses the value of otherdir) can break depending on the value of mydir and which operating system is being used. In Windows, drive roots like C:\ are usually returned with a trailing slash, while other folders, like C:\Windows, are not. There are all sorts of other edge cases that can cause bugs if you do not handle paths properly.

As another strike against it, adding paths has the same downsides as adding strings, including poor performance and readability. Refer to the String concatenation section from earlier.

These problems are totally unnecessary. Python includes a robust set of path manipulation functionality in the os.path module. Use it. The correct version of the preceding code would be:

otherdir = os.path.join(mydir, '..', '..')

The os.path module also includes a number of OS-dependent variables, such as os.path.sep (the folder separator character) and os.path.pathsep (the separator between paths in an environment variable). There are also higher-level path manipulation libraries available, such as the pymel.util.common.path module.

Finally, you will find that doing path manipulation properly creates code that is easier to read, and you will be unable to tolerate building paths with inferior techniques.