如何在 Python 中获取当前文件目录的完整路径?
Python 的 OS 模块包含用于创建和删除目录(文件夹)、检索其内容、更改和识别当前目录等的功能。为了与底层操作系统交互,您必须首先导入 os 模块。
可以在 Python 中获取正在执行的程序代码的位置(路径)。py 使用 __file__。__file__ 可用于根据当前文件的位置读取其他文件。
示例
在以下示例中,os.getcwd() 函数生成一个包含 Python 正在运行的当前工作目录的绝对路径的字符串 str。
#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() 方法返回 tail 部分。
示例
在以下示例中,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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP