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...