OS library Python - Locating Directories

Asked

Viewed 660 times

1

I’m learning how to find directories in Python and 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 in the python language is used __file__ to refer to the current file?

How this command relates to all syntax?

What’s the downside of using os.getcwd()?

2 answers

1


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

Do 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 exit will be:

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

I mean, it’s not the same.

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

0

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

line 3 and 6 expressions are just different ways to solve the same problem, the disadvantage of line 3 is that you are running 2 methods and line 6 only 1.

  • They’re not the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.