简体   繁体   English

获取当前Python文件的路径

[英]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?例如,如果我有以下文件: X/foo.pyY/bar.py ,并且我正在运行python3 foo.pyfoo.py导入bar.py ,并且在bar.py我得到父目录,我希望它是 Y 而不是 X。我该怎么做? currently, I get X with path = pathlib.Path(__file__).parent.resolve()目前,我用path = pathlib.Path(__file__).parent.resolve()得到 X

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.这将返回当前 py 文件的绝对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中获取当前执行文件的路径? - How do I get the path of the current executed file in Python? Python中如何使用另一个文件获取当前路径 - How to get the current path using another file in Python Python - 在当前 Windows 资源管理器中获取所选文件的路径 - Python - Get Path of Selected File in Current Windows Explorer vscode 从 python 脚本中获取当前文件的路径 - vscode get path of current file from inside python script 如果从 python 中的快捷方式启动,如何获取当前文件路径? - How to get current file path if launched from a shortcut in python? 有没有办法获取不在当前工作目录中的文件的绝对路径(在 Python 中)? - Is there a way to get an absolute path of a file which is not in the current working directory (in Python)? 如何在 Windows 批处理/Python 文件中获取当前目录的路径? - How to get path of current directory in Windows Batch/Python file? 这个获取当前文件路径的 Python 代码将在 Linux 上工作吗? - This Python code to get the current file path will work on Linux? 在Python中获取当前TTY的路径 - Get the path of the current TTY in Python pytest获取当前测试文件的文件路径 - pytest get the file path of current test file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM