To extract only directories from the absolute path of the current file

Asked 2 years ago, Updated 2 years ago, 87 views

I just want to find the absolute path to the directory os.path.abspath(_file__) is C:\python27\\test.py It even contains files.

C:\\python27\' How do I find out the directory path only like this?

python filesystems

2022-09-22 22:23

2 Answers

When determining the directory where the script is located,

os.path.dirname(os.path.Abspath early can be to extract the directory as ,

(__ file and __ SERVER,)).

To find out the directory you are working on os.getcwd() You have to write something.

import os

print("dirname:\t" + os.path.dirname(os.path.abspath(__file__)))
print("getcwd:\t\t" + os.getcwd())

Output:

dirname:    /Users/username/PycharmProjects/tempdir
getcwd:     /Users/username/PycharmProjects/tempdir


2022-09-22 22:23

import sys, os

print(sys.path) # System path

print(os.getcwd()) #

in the current directory

print(os.path.realpath(_file_)#File

print(os.path.dirname(os.path.realpath(_file_)))#directory where the file is located


2022-09-22 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.