python路径获取那些事儿

95 阅读2分钟

一、获取当前路径

1、os.getcwd()

在Python中,为了获得当前的目录与当前正在执行的脚本的文件路径,你可以使用来自于Python标准库的osos.path模块 示例如下:

import os

# Get the current directory
current_directory = os.getcwd()

# Print the current directory
print("The current directory is:", current_directory)

在该示例中,我们导入os模块,使用os.getcwd()方法来获得当前的路径(字符串的形式)。然后我们打印了当前的路径

需要注意: 获取当前路径使用os.getcwd()并不总是有效的,实际上这个方法显示的是执行脚本的路径。getcwd == get current working directory,即获取当前工作目录。

例如,有个脚本test.py中在D:\test目录下,test.py内容如下:

import os
print(os.getcwd())

此时获取到的路径为D:\test

当在E盘下执行python D:\test\test.py时,获取到的路径为E:\ 故一般不建议使用该方法获取当前路径,当代码路径迁移或执行路径发生变化时,可能会出现问题。

2、os.path.abspath(file)

为了获得当前正在执行的脚本的文件路径,你可以将__file__属性与os.path模块结合使用:

import os

# Get the absolute path of the currently executing script
script_path = os.path.abspath(__file__)

# Print the script path
print("The script path is:", script_path)

在这个示例中,我们使用__file__属性,该属性将会返回当前正在执行的脚本的相对路径,以及 os.path.abspath()方法来将此相对路径转换为一个绝对路径,然后我们打印了这个脚本路径。

3、os.path.realpath(file)

请记住, __file__属性可能工作不如预期,当以交互形式运行该脚本时,例如在一个Python shell或一个Jupyter Notebook中。在这样的场景下,你可以使用os.path.realpath()与 __file__ 属性来获得正确的文件路径:

import os

# Get the absolute path of the currently executing script
script_path = os.path.realpath(__file__)

# Print the script path
print("The script path is:", script_path)

在这个示例中,我们使用 os.path.realpath()方法与__file__属性,来获得当前正在执行的脚本的绝对路径