查找当前目录和文件的目录[重复]
- 2024-12-03 08:44:00
- admin 原创
- 195
问题描述:
我如何确定:
当前目录(运行 Python 脚本时我在 shell 中的位置),以及
我正在执行的 Python 文件在哪里?
解决方案 1:
要获取 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)
(返回“pathname 的目录名称path
”)os.getcwd()
(返回“代表当前工作目录的字符串”)os.chdir(path)
(“将当前工作目录更改为path
”)
解决方案 2:
当前工作目录: os.getcwd()
并且该__file__
属性可以帮助您找出正在执行的文件的位置。这篇 Stack Overflow 帖子解释了一切: 如何在 Python 中获取当前执行文件的路径?
解决方案 3:
您可能会发现这很有用作为参考:
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "
")
print("This file path, relative to os.getcwd()")
print(__file__ + "
")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "
")
print("This file directory and name")
path, filename = os.path.split(full_path)
print(path + ' --> ' + filename + "
")
print("This file directory only")
print(os.path.dirname(full_path))
解决方案 4:
该pathlib
模块在 Python 3.4 中引入(PEP 428 — pathlib 模块 — 面向对象的文件系统路径),使与路径相关的体验更好。
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
(建议.resolve()
在之前调用.parent
):
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()
方法,但后一种选项要求您更改旧代码:
文件脚本/2.py
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 - 添加文件系统路径协议PathLike
,在 Python 3.6 中实现,为函数添加了对对象的支持open
,因此现在您可以将Path
对象open
直接传递给函数:
python3.6 scripts/2.py
OK
解决方案 5:
获取当前目录的完整路径
>>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”
解决方案 6:
Pathlib可以以这种方式使用来获取包含当前脚本的目录:
import pathlib
filepath = pathlib.Path(__file__).resolve().parent
解决方案 7:
如果您尝试查找当前所在文件的当前目录:
与操作系统无关的方式:
dirname, filename = os.path.split(os.path.abspath(__file__))
解决方案 8:
获取当前目录的完整路径:
os.path.realpath('.')
解决方案 9:
如果您使用的是 Python 3.4,那么有一个全新的高级pathlib
模块,允许您方便地调用它pathlib.Path.cwd()
来获取Path
代表当前工作目录的对象,以及许多其他新功能。
关于此新 API 的更多信息可以在这里找到。
解决方案 10:
回答 #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__)
解决方案 11:
我认为找到当前执行上下文的名称的最简洁的方法是:
current_folder_path, current_folder_name = os.path.split(os.getcwd())
解决方案 12:
对于问题 1,使用os.getcwd() # Get working directory
和os.chdir(r'D:Steamsteamappscommon') # Set working directory
sys.argv[0]
对于问题 2,我建议使用,因为sys.argv
是不可变的,因此始终返回当前文件(模块对象路径)并且不受的影响os.chdir()
。您也可以这样做:
import os
this_py_file = os.path.realpath(__file__)
# vvv Below comes your code vvv #
但是,该代码片段sys.argv[0]
在由 PyInstaller 编译时将无法工作或者工作异常,因为魔法属性未在__main__
级别中设置,并且sys.argv[0]
是调用可执行文件的方式(这意味着它会受到工作目录的影响)。
解决方案 13:
如果您正在搜索当前执行的脚本的位置,您可以使用sys.argv[0]
来获取完整路径。