OS library Python - Finding Directories

1

I'm learning how to locate directories in Python and I came across the following code:

import os

dir_path = os.path.dirname(os.path.realpath(__file__))
print(dir_path)

cwd = os.getcwd()
print(cwd)

Why does the Python language use __file__ to refer to the current file?

How does this command relate to all syntax?

What is the disadvantage in using os.getcwd() ?

    
asked by anonymous 01.08.2017 / 06:00

2 answers

1

You only get the same return in both cases because you are running the script directly in the same working directory.

Take the test yourself, put this script in some other directory. Open a prompt on the desktop and run the script from that workplace, for example:

py C:\meus-scripts\script-do-arduin.py

The output will be:

C:\meus-scripts
C:\Users\Arduin\Desktop

That is, it is not the same thing.

os.getcwd returns a string representing the current working directory, so care should be taken when using os.chdir() . Already __file__ contains the path of the file in which the module was loaded (if it is loaded from a file).

    
02.08.2017 / 18:55
-1

The file expression is a "magic" variable that returns a string containing the current file name.

The expressions in line 3 and 6 are just different ways of solving the same problem, the disadvantage of line 3 is that you are executing 2 methods and in line 6 only 1.

    
02.08.2017 / 18:16