Python 如何获取当前文件目录的完整路径

Python 如何获取当前文件目录的完整路径

Python的OS模块包括用于创建和删除目录(文件夹)、检索它们的内容、修改和标识当前目录等功能。要与底层操作系统进行交互,首先必须导入os模块。

可以通过Python代码获取执行程序代码的位置(路径)。使用file可以基于当前文件的位置读取其他文件。

示例

在以下示例中,os.getcwd()函数生成一个字符串str,其中包含Python操作的当前工作目录的绝对路径。

#Python program to get the path of the current working directory
#Program to get the path of the file
#Using getcwd()
#Importing the os module
import os
print(' The current working directory is: ', os.getcwd())
print('File name is: ', __file__)

输出

在执行上述程序时,生成以下输出。

The current working directory: C:\Users\pranathi\Desktop\python prog
File name: c:\users\pranathi\desktop\python prog\untitled1.py

使用os.path.basename()

在Python中, os.path.basename() 方法用于获取路径的基本名称。为了将提供的路径拆分成一对,该方法在内部使用 os.path.split() 方法(head,tail)。在将提供的路径分离为(head,tail)对之后, os.path.basename() 方法返回尾部部分。

示例

在下面的示例中,使用 os.path.dirname() 方法从提供的路径中检索目录名。

#python program to find the basename and dirname of the path
import os
print('basename of the file: ', os.path.basename(__file__))
print('dirname of the file: ', os.path.dirname(__file__))

输出

执行以上程序后,会生成以下输出。

basename of the file: untitled1.py
dirname of the file: c:\users\pranathi\desktop\python prog

获取目录的绝对路径

绝对路径是指文件或文件夹的位置与当前工作目录无关,实际上是相对于根目录而言。

示例

以下示例是一个用Python编写的程序,用于查找绝对路径。

#python program to find the absolute path
import os
print('absolute path of the file: ', os.path.abspath(__file__))
print('absolute path of dirname: ', os.path.dirname(os.path.abspath(__file__)))

在Python中使用os.getcwd方法

OS模块的getcwd()方法返回一个字符串,其中包含当前工作目录的绝对路径。输出字符串中不包含尾部的斜杠字符。

示例

在下面的示例中,导入os模块并使用getcwd()函数获取当前工作目录。使用print()函数打印出该目录。

#importing the os module
import os

#to get the current working directory
directory = os.getcwd()

print(directory)

输出

执行上述程序后,生成以下输出。

C:\Users\pranathi\Desktop\python prog

示例

输出结果将根据您所在的目录而不同,但它将始终以根文件夹(例如,D:) 和一个以a为前缀的目录开头。

import os
absolute_path = os.path.abspath(__file__)
print("Full path: " + absolute_path)
print("Directory Path: " + os.path.dirname(absolute_path))

输出

在执行上述程序后,会生成以下输出结果。

Full path: c:\users\pranathi\desktop\python prog\untitled1.py
Directory Path: c:\users\pranathi\desktop\python prog

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程