Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is os.path.join(os.path.dirname(__file__), 'data') in Linux/Windows?

Tags:

python

Where is the folder the following code is creating according different operating systems?

data_dir = os.path.join(os.path.dirname(__file__), 'data')
if not os.path.exists(data_dir):
    import generate_data
    os.mkdir(data_dir)

Is it '/path/to/file/data' ?

like image 324
Harry Avatar asked Aug 23 '12 12:08

Harry


People also ask

What does os path dirname (__ file __)?

dirname() method in Python is used to get the directory name from the specified path.

What does os path Dirname os path Realpath (__ file __ do?

os. path. realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")

What is os path Dirname?

os.path. dirname(path) Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split() .

What is os path join?

os. path. join combines path names into one complete path. This means that you can merge multiple parts of a path into one, instead of hard-coding every path name manually.


2 Answers

__file__ is the full path to where the file that contains the code is running; so its going to be the directory from which the file that contains the snippet was executed.

like image 84
Burhan Khalid Avatar answered Oct 05 '22 08:10

Burhan Khalid


os.path.dirname gives you the directory its argument is in, and os.path.join appends a file or directory to the given directory.

os.path provides you with a platform-independent way to modify file and directory paths, making use of the appropriate types of slashes.

So yes, this will create a 'data' directory (if it doesn't already exist) within the same directory as the source file from which this code is run.

like image 44
P Daddy Avatar answered Oct 05 '22 07:10

P Daddy