Python basics -- os.path module

How to use the common os.path module
os.path.dirname(path) Returns the file directory
os.path.abspath(path) Returns the absolute path
os.path.join(path1,path2) Combines the directory and file name into one path

Chestnut: The current file path is: E:/Project/untitled/study/test.py
1. os.path.dirname() usage:

import os
print(os.path.dirname(__file__))	# 返回当前文件的目录
print(os.path.dirname(os.path.dirname(__file__)))	# 返回当前文件的上级目录
print(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))	# 返回当前文件的上上级目录

The input result is:
insert image description here

2. os.path.abspath() usage:

import os
print(os.path.abspath(__file__))    # 返回绝对路径
print(os.path.abspath(os.path.dirname(__file__)))   # 返回当前文件目录的绝对路径
print(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))  # 返回当前文件上级目录的绝对路径

The output is:

3. os.path.join() usage:

import os
path1 = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))  # 返回当前文件上级目录的绝对路径
print(path1)
path2 = r"sql\connect_sql.py"
print(os.path.join(path1, path2))    # 将path1和path2重新组成一个路径

The output is:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45422695/article/details/121247742