這里主要記錄下os.path.join()的用法
目錄結構如下
在readconfig.py中進行試驗,如下
1.使用os.path.realpath(__file__)獲取文件所在目錄
import os
print(os.path.realpath(__file__))
運行結果
E:\Crawler\common\readconfig.py 運行結果顯示 “路徑+文件名”
2. os.path.split(path),將path分割成目錄和文件名二元組返回
在上一步的基礎上運用split方法
1. print(os.path.split(os.path.realpath(__file__)))
或者直接使用絕對路徑看的更清楚些
2. print(os.path.split('E:\Crawler\common\\readconfig.py'))
那么如果只取目錄的話,如下
3. print(os.path.split(os.path.realpath(__file__))[0])
運行結果
1、2的結果 ('E:\\Crawler\\common', 'readconfig.py') 3的結果 E:\Crawler\common
3.os.path.abspath('.'), 獲取當前文件所在路徑
print(os.path.abspath('.'))
運行結果
E:\Crawler\common
4.os.path.dirname(path),返回path的目錄
1. print(os.path.dirname('E:\Crawler\common\\readconfig.py'))
結果:E:\Crawler\common
2. print(os.path.dirname('E:\Crawler\common'))
結果:E:\Crawler
所以 os.path.dirname(os.path.abspath('.')) 表示獲取當前文件所在目錄的上一級目錄,即項目所在目錄E:\Crawler
結果:E:\Crawler
5.os.path.join(), 用於路徑拼接,將多個路徑組合后返回,第一個絕對路徑之前的參數將被忽略
所謂第一個絕對路徑,是從“尾部向頭部讀,所得到的第一個絕對路徑”,以 “\” 為標識
print(os.path.join('E:\Crawler', "config.ini"))
結果:E:\Crawler\config.ini
print(os.path.join('E:\Crawler', 'D:\\aa', "config.ini"))
結果:D:\aa\config.ini
print(os.path.join('/home/mnt','/home/mnt/attach','/home/a/b/c'))
結果:/home/a/b/c
print(os.path.join('/local', '\\aa', "/config.ini"))
結果:/config.ini