Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python)是否有任何方法可以获取某个文件所在的当前目录位置?_Python - Fatal编程技术网

Python)是否有任何方法可以获取某个文件所在的当前目录位置?

Python)是否有任何方法可以获取某个文件所在的当前目录位置?,python,Python,我知道os.get_cwd返回当前目录。但问题是,它返回执行python的目录,而不是其中存在的特定文件 例如,下面是目录结构: my_test_dir ├── __init__.py ├── main.py └── test1 ├── __init__.py └── util.py 假设我在util.py中插入printos.get_cwd。和main.py import util。如果我在我的测试目录中运行main.py,那么它将打印我的测试目录,而不是我的测试目录/tes

我知道os.get_cwd返回当前目录。但问题是,它返回执行python的目录,而不是其中存在的特定文件

例如,下面是目录结构:

my_test_dir
├── __init__.py
├── main.py
└── test1
    ├── __init__.py
    └── util.py
假设我在util.py中插入printos.get_cwd。和main.py import util。如果我在我的测试目录中运行main.py,那么它将打印我的测试目录,而不是我的测试目录/test1,因为我在测试目录中执行这个python程序

我想做的是让它打印我的测试目录/test1


有什么方法可以做到这一点吗?

使用Windows操作系统时要小心,为了避免任何类型的麻烦,您可以执行以下操作:

print(os.path.dirname(__file__))
import os
os.path.dirname(os.path.abspath(__file__))
可能重复的