我如何确定:
- 当前目录(在运行Python脚本时所在的shell中),以及
- 我正在执行的Python文件的位置?
要获取 Python 文件所在目录的完整路径,请在该文件中编写以下代码:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
请注意,如果您已经使用 os.chdir()
来更改当前工作目录,则上述咒语将不起作用。因为 __file__
常量的值是相对于当前工作目录的,并且不会受到 os.chdir()
调用的影响。
要获取当前工作目录,请使用
import os
cwd = os.getcwd()
上面使用的模块、常量和函数的文档参考资料:
os
和 os.path
模块。__file__
常量os.path.realpath(path)
(返回"指定文件名的规范化绝对路径,消除路径中的任何符号链接")os.path.dirname(path)
(返回"路径名path
的目录名")os.getcwd()
(返回"表示当前工作目录的字符串")os.chdir(path)
("将当前工作目录更改为path
")dirname
反转realpath
时路径是相同的,但当文件(或其目录)实际上是符号链接时,它将会有所不同。 - LekensteynNameError: name '__file__' is not defined
。如何解决? - Mohammad ElNesrimport 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))
__file__
在这里代表什么意思?但它对我不起作用。 - Alex Raj Kaliamoorthy__file__
是模块对象的一个属性。你需要在 Python 文件内运行代码,而不是在 REPL 上运行。 - Daniel Reispathlib
模块是在Python 3.4中引入的(PEP 428 — The pathlib module — object-oriented filesystem paths),它使得与路径相关的操作变得更加简单易用。
pwd
/home/skovorodkin/stack
tree
.
└── scripts
├── 1.py
└── 2.py
Path.cwd()
:from pathlib import Path
print(Path.cwd()) # /home/skovorodkin/stack
Path.resolve()
方法获取脚本文件的绝对路径:print(Path(__file__).resolve()) # /home/skovorodkin/stack/scripts/1.py
要获取脚本所在目录的路径,请访问 .parent
(建议在调用 .parent
之前调用 .resolve()
):
print(Path(__file__).resolve().parent) # /home/skovorodkin/stack/scripts
请记住,在某些情况下,__file__
是不可靠的:如何在Python中获取当前执行文件的路径?。
Path.cwd()
、Path.resolve()
和其他Path
方法返回路径对象(在我的情况下是PosixPath
),而不是字符串。在Python 3.4和3.5中,这会导致一些问题,因为open
内置函数只能处理字符串或字节对象,并不支持Path
对象,所以你必须将Path
对象转换为字符串或使用Path.open()
方法,但后一种选项需要更改旧代码:
from pathlib import Path
p = Path(__file__).resolve()
with p.open() as f: pass
with open(str(p)) as f: pass
with open(p) as f: pass
print('OK')
python3.5 scripts/2.py
Traceback (most recent call last):
File "scripts/2.py", line 11, in <module>
with open(p) as f:
TypeError: invalid file: PosixPath('/home/skovorodkin/stack/scripts/2.py')
正如您所看到的,open(p)
在Python 3.5中无法使用。
PEP 519 — 添加文件系统路径协议,在Python 3.6中实现,添加了对PathLike
对象的支持到open
函数,因此现在您可以直接将Path
对象传递给open
函数:
python3.6 scripts/2.py
OK
app_path = Path(__file__).resolve().parent.parent.parent
与 ../../../
并列使用,如果需要的话。 - shackerpython3.5
"和"python3.6
"的可执行文件(或等效文件)?Ubuntu Ubuntu MATE 20.04 (Focal Fossa)没有(至少默认情况下没有)。它有名为"python3
"和"python2
"的可执行文件(但没有名为"python
"的 - 这会导致某些问题)。 - Peter Mortensenpython3.x
符号链接。也许我认为这会使代码片段对读者更清晰一些。 - skovorodkin获取当前目录的完整路径
>>import os
>>print os.getcwd()
输出:"C:\Users\admin\myfolder"
只获取当前目录的文件夹名称
>>import os
>>str1=os.getcwd()
>>str2=str1.split('\\')
>>n=len(str2)
>>print str2[n-1]
输出:"myfolder"
os.getcwd().split('\\')[-1]
- imkost可以使用Pathlib这样的方式来获取包含当前脚本的目录:
import pathlib
filepath = pathlib.Path(__file__).resolve().parent
app_path = Path(__file__).resolve().parent.parent.parent
用作../../../
的并列方法。 - shackerNameError: name '__file__' is not defined
,如何解决? - XYZdirname, filename = os.path.split(os.path.abspath(__file__))
获取当前目录的完整路径:
os.path.realpath('.')
os.getcwd()
和os.path.realpath('.')
返回完全相同的路径字符串。 - Leevopathlib
模块可让您方便地调用pathlib.Path.cwd()
来获取代表当前工作目录的Path
对象,以及许多其他新功能。pathlib2
库:https://pypi.python.org/pypi/pathlib2/。 - Eyal Levin问题1的答案:
如果你想获取当前目录,可以这样做:
import os
os.getcwd()
如果你只想要任何文件夹名称,并且你已经有了该文件夹的路径,请按照以下步骤操作: 如果您想要仅获取文件夹名称并且拥有该文件夹的路径,请执行以下操作:
def get_folder_name(folder):
'''
Returns the folder name, given a full folder path
'''
return folder.split(os.sep)[-1]
答案 #2:
import os
print os.path.abspath(__file__)
os.getcwd()
”。唉。 - Karl Knechtel