In relation to another question, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ‘.\foo.py’ in *nix. However, apparently Windows likes to have the path hard-coded, e.g. ‘C:\Python_project\foo.py’.
What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won’t match the drive letter in the code.
I want the program to be cross-platform, but I expect I may have to use os.name or something to determine which path code block to use.
Simple answer: You work out the absolute path based on the environment.
What you really need is a few pointers. There are various bits of runtime and environment information that you can glean from various places in the standard library (and they certainly help me when I want to deploy an application on windows).
So, first some general things:
os.path– standard library module with lots of cross-platform path manipulation. Your best friend. ‘Follow the os.path’ I once read in a book.__file__– The location of the current module.sys.executable– The location of the running Python.Now you can fairly much glean anything you want from these three sources. The functions from os.path will help you get around the tree:
os.path.join('path1', 'path2')– join path segments in a cross-platform wayos.path.expanduser('a_path')– find the patha_pathin the user’s home directoryos.path.abspath('a_path')– convert a relative path to an absolute pathos.path.dirname('a_path')– get the directory that a path is inSo combining this, for example:
And running it:
Now for your specific case, it seems you are slightly confused between the concept of a ‘working directory’ and the ‘directory that a script is in’. These can be the same, but they can also be different. For example the ‘working directory’ can be changed, and so functions that use it might be able to find what they are looking for sometimes but not others.
subprocess.Popenis an example of this.If you always pass paths absolutely, you will never get into working directory issues.