简体   繁体   中英

Get the path of the current Python file

I am trying to the get the path of the directory of the current running file. For example, if I the following files: X/foo.py and Y/bar.py , and I am running python3 foo.py and foo.py imports bar.py , and in bar.py I get the parent directory, I want it to be Y and not X. How do I do that? currently, I get X with path = pathlib.Path(__file__).parent.resolve()

This question already was answered here: Find the current directory and file's directory

What you need to do is the following:

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

This will return the absolute path to the current py-file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM