在日常开发工作中,我们经常需要知道项目或者项目中某个文件所在的路径,这是我们可以使用 os.getcwd()
或 os.path.abspath()
来输出路径。
1. os.getcwd()
获取当前脚本的工作目录,也就是在哪个目录下运行这个程序。
使用方式:
os.getcwd()
- 入参:os.getcwd()不接收任何参数,否则python会抛出TypeError。
- 返回值:返回值为表示文件工作路径的字符串str。
使用样例:
import os
current_dir = os.getcwd()
print(current_dir)
# 输出:/home/usr/test-project
2. os.path.abspath()
获取当前脚本存放的绝对路径。
使用方式:
os.path.abspath(path)
- 入参:参数path一般情况下使用相对路径的写法,因为如果是绝对路径的话,os.path.abspath()方法会返回该绝对路径本身。
- 返回值:返回值为绝对路径的字符串str。
使用样例1: 入参为相对路径,返回文件所在绝对路径。
absolute_dir_1 = os.path.abspath(__file__) # __file__ 获取当前脚本存放的绝对路径
print(absolute_dir_1)
# 输出:/home/usr/test-project/test.py
absolute_dir_2 = os.path.abspath('test.py')
print(absolute_dir_2)
# 输出:/home/usr/test-project/test.py
使用样例2: 入参为绝对路径,返回该绝对路径本身。
absolute_dir_3 = os.path.abspath('/home/usr/test.py')
print(absolute_dir_3)
# 输出:/home/usr/test.py
这里,入参如果是绝对路径的话,os.path.abspath()方法会返回该绝对路径本身。