os.path.expanduser - a good start - the host ~/ expands to the "user's home directory", which is a computer by a reasonable heuristic for both Unix-y systems and Windows. Of course, you do not want to directly put your file in the house, but a subdirectory of this (which you will need to do if it does not already exist) is reasonable by default.
Of course, allow this parameter to be overridden with the environment variable or command line flag passed to your program, as some platforms are rather scarce as to where, by convention, the application should park such auxiliary data files.
Edit : OP requests an example:
Suppose I wanted this in ~ / tempfoler / and the file transferred to it was args1.txt?
I would suggest finding the exact path through a function such as:
import errno import os def getfilepath(filename, foldername='tempfoler', envar='MYAPPDIR'):
There are some design options built in here - they cause exceptions for all kinds of problems (higher levels can catch and process them accordingly, for example, ask the user for an alternative - this lower level function cannot do it right!), Return the path to the file that may or may not exist (thus, it is suitable for reading an existing file or writing a new one), etc.
You can also do fewer checks and rely more on automatic exceptions that occur for all types of anomalies (or vice versa), I just think it puts a reasonable balance (and, of course, it's easy for you to set up if you prefer a slightly different approach to such issues). But the key idea is to always focus on what can go wrong and how to deal with it (often with higher-level code, the only suitable point for a possible user request for alternatives) to make your software reliable.
source share