Find the current directory and file's directory
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction
--
Chapters
00:00 Find The Current Directory And File'S Directory
00:18 Accepted Answer Score 4781
01:24 Answer 2 Score 391
01:47 Answer 3 Score 368
02:06 Answer 4 Score 84
02:28 Thank you
--
Full question
https://stackoverflow.com/questions/5137...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #directory
#avk47
ACCEPTED ANSWER
Score 4781
To get the full path to the directory a Python file is contained in, write this in that file:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(Note that the incantation above won't work if you've already used os.chdir() to change your current working directory, since the value of the __file__ constant is relative to the current working directory and is not changed by an os.chdir() call.)
To get the current working directory use
import os
cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
- The
osandos.pathmodules. - The
__file__constant os.path.realpath(path)(returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")os.path.dirname(path)(returns "the directory name of pathnamepath")os.getcwd()(returns "a string representing the current working directory")os.chdir(path)("change the current working directory topath")
ANSWER 2
Score 391
Current working directory: os.getcwd()
And the __file__ attribute can help you find out where the file you are executing is located. This Stack Overflow post explains everything: How do I get the path of the current executed file in Python?
ANSWER 3
Score 368
You may find this useful as a reference:
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, relative to os.getcwd()")
print(__file__ + "\n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")
print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "\n")
print("This file directory only")
print(os.path.dirname(full_path))
ANSWER 4
Score 84
To get the current directory full path
>>import os >>print os.getcwd()Output: "C :\Users\admin\myfolder"
To get the current directory folder name alone
>>import os >>str1=os.getcwd() >>str2=str1.split('\\') >>n=len(str2) >>print str2[n-1]Output: "myfolder"