ChatGPT解决这个技术问题 Extra ChatGPT

查找当前目录和文件的目录[重复]

这个问题在这里已经有了答案:如何正确确定当前脚本目录? (16个回答) 如何知道/更改 Python shell 中的当前目录? (7 个回答) 4 年前关闭。

我如何确定:

当前目录(运行 Python 脚本时我在终端中的位置),以及我正在执行的 Python 文件在哪里?


M
Mark Amery

要获取包含 Python 文件的目录的完整路径,请在该文件中写入:

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

(请注意,如果您已经使用 os.chdir() 更改当前工作目录,则上述咒语将不起作用,因为 __file__ 常量的值是相对于当前工作目录的,并且不会被 {1 } 称呼。)

要获取当前工作目录,请使用

import os
cwd = os.getcwd()

上面使用的模块、常量和函数的文档参考:

os 和 os.path 模块。

__file__ 常量

os.path.realpath(path)(返回“指定文件名的规范路径,排除路径中遇到的任何符号链接”)

os.path.dirname(path) (返回“路径名路径的目录名”)

os.getcwd() (返回“代表当前工作目录的字符串”)

os.chdir(path) ("改变当前工作目录为路径")


当我使用它附加到 sys.path 时,我讨厌它。我现在觉得好脏。
如果从 IDE(比如 IDLE)调用 file 将不起作用。建议使用 os.path.realpath('./') 或 os.getcwd()。这里最好的分析器:stackoverflow.com/questions/2632199/…
@Neon22 可能满足某些需求,但我觉得应该注意的是,这些东西根本不一样——文件可以在工作目录之外。
@Moberg 使用 dirname 反转 realpath 时,路径通常是相同的,但当文件(或其目录)实际上是符号链接时,路径会有所不同。
它得到一个错误 NameError: name '__file__' is not defined。如何解决这个问题?
P
Peter Mortensen

Current working directoryos.getcwd()

__file__ attribute 可以帮助您找出正在执行的文件所在的位置。这篇 Stack Overflow 帖子解释了一切:How do I get the path of the current executed file in Python?


C
Community

作为参考,您可能会发现这很有用:

import 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__ 在这里表示什么?它对我不起作用。
__file__ 是模块对象的属性。您需要在 Python 文件中运行代码,而不是在 REPL 上。
P
Peter Mortensen

pathlib 模块 introduced in 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__ 在某些情况下并不可靠:How do I get the path of the current executed file in 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 — Adding a file system path protocol 在 Python 3.6 中实现,向 open 函数添加了对 PathLike 对象的支持,因此现在您可以将 Path 对象直接传递给 open 函数:

python3.6 scripts/2.py

OK

另请注意,这些方法是可链接的,因此您可以根据需要将 app_path = Path(__file__).resolve().parent.parent.parent../../../ 并行使用。
哪个系统具有名为“python3.5”和“python3.6”的可执行文件(或等效文件)? Ubuntu Ubuntu MATE 20.04 (Focal Fossa) 没有(至少默认情况下没有)。它具有名称为“python3”和“python2”的可执行文件(但不是“python” - 这会导致 some things to break
@PeterMortensen,感谢您的更正。我不记得当时我是否真的有 python3.x 符号链接。也许我认为它会使片段对读者更清楚一些。
P
Peter Mortensen

获取当前目录全路径 >>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]
对于 Windows,最好使用 os.sep 而不是硬编码:os.getcwd().split(os.sep)[-1]
这种方法的问题在于,如果您从不同的目录执行脚本,您将获得该目录的名称而不是脚本的名称,这可能不是您想要的。
对,托管文件的当前目录可能不是您的 CWD
P
Peter Mortensen

Pathlib 可用于获取包含当前脚本的目录:

import pathlib
filepath = pathlib.Path(__file__).resolve().parent

我喜欢这个解决方案。但是可能会导致一些 Python 2.X 问题。
对于 python 3.3 和更早版本,必须安装 pathlib
@Kimmo 您应该使用 Python 2 代码的唯一原因是将其转换为 Python 3。
@kagnirick 同意,但仍有人不同意。我使用 Python 3.6 使用格式化字符串文字 (PEP 498) 编写所有新内容,这样就不会有人将它们推送到 Python2。
另请注意,这些方法是可链接的,因此您可以根据需要将 app_path = Path(__file__).resolve().parent.parent.parent../../../ 并行使用。
A
Ashwini Chaudhary

如果您尝试查找当前所在文件的当前目录:

操作系统不可知的方式:

dirname, filename = os.path.split(os.path.abspath(__file__))

J
Jazzer

如果您使用的是 Python 3.4,则有全新的高级 pathlib 模块,它允许您方便地调用 pathlib.Path.cwd() 来获取代表当前工作目录的 Path 对象,以及许多其他新功能。

有关此新 API 的更多信息,请参阅 here


对于 Python 版本 < 3.4 你可以使用pathlib2pypi.python.org/pypi/pathlib2
L
Logovskii Dmitrii

获取当前目录完整路径:

os.path.realpath('.')

这个可以在 jupyter iPython notebook 中工作('__file__' 和 getcwd 不会)
仍然有效。感谢未来的@OliverZendel!
我正在使用 Jupyter Notebook 远程工作:os.getcwd() 和 `os.path.realpath('.') 返回完全相同的字符串路径。
@Leevo:重点是?
B
Blairg23

回答#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__)

P
Peter Mortensen

我认为查找当前执行上下文名称的最简洁方法是:

current_folder_path, current_folder_name = os.path.split(os.getcwd())

E
Eric Leschinski

如果您正在搜索当前执行脚本的位置,您可以使用 sys.argv[0] 获取完整路径。


这是错误的。 sys.argv[0] 不必包含执行脚本的完整 路径。
P
Peter Mortensen

对于问题 1,使用 os.getcwd() # Get working directoryos.chdir(r'D:\Steam\steamapps\common') # Set working directory

我建议对问题 2 使用 sys.argv[0],因为 sys.argv 是不可变的,因此总是返回当前文件(模块对象路径)并且不受 os.chdir() 的影响。你也可以这样做:

import os
this_py_file = os.path.realpath(__file__)

# vvv Below comes your code vvv #

但是,当 PyInstaller 编译时,该代码段和 sys.argv[0] 将不起作用或工作异常,因为魔术属性未在 __main__ 级别设置,并且 sys.argv[0] 是调用可执行文件的方式(这意味着它会受到工作目录)。