一、概述
Python中的os.path模塊提供了許多用於處理文件路徑的函數,而其中的os.path.relpath()用於獲得相對路徑。具體來說,os.path.relpath()用於返回從start到path的相對路徑。
其中start是當前工作目錄(或所給路徑)與path的共同的父目錄,如果start未給出,則使用當前工作目錄作為起點。如果path和start相同,返回當前工作目錄的名稱(即’.’)。
二、函數簽名
os.path.relpath(path[, start])
參數說明:
- path: 要獲取相對路徑的路徑字符串。
- start: 起始路徑字符串,按照默認的情況下是當前工作目錄。
返回值:返回從start到path的相對路徑。
三、示例代碼1
以下是一個使用os.path.relpath()函數的簡單示例,目標路徑為’/Users/Admin/test/test.py’,當前工作目錄為’/Users/Admin’:
import os path = '/Users/Admin/test/test.py' print(os.path.relpath(path)) # 輸出:'test/test.py'
在這個示例中,由於當前工作目錄與目標路徑的共同父目錄為’/Users/Admin’,因此os.path.relpath()返回’test/test.py’。
四、示例代碼2
下面的示例通過啟動Python解釋器來演示,其中腳本放在’d:/workspace/sample/’路徑下,圖像文件放在’d:/workspace/sample/images/’路徑下:
python3 start.py from os.path import relpath if __name__ == '__main__': start_path = 'd:/workspace/sample/' target_path = 'd:/workspace/sample/images/test.jpg' relative_path = relpath(target_path, start_path) print(relative_path)
運行結果為:
images/test.jpg
這個示例中,start_path為’d:/workspace/sample/’,而target_path為’d:/workspace/sample/images/test.jpg’。因此,我們可以計算出相對路徑為’images/test.jpg’。
五、示例代碼3
下面的示例演示了如何使用相對路徑來訪問目標文件。
import os # Get the current working directory cwd = os.getcwd() # Construct path name of input file input_file = os.path.join(cwd, 'datafiles/input.txt') # Construct path name of output file output_dir = os.path.join(cwd, 'results') output_file = os.path.join(output_dir, 'output.txt') if not os.path.exists(output_dir): os.mkdir(output_dir) with open(input_file, 'r') as fin, open(output_file, 'w') as fout: fout.write(fin.read()) print('Finished writing the output file:', os.path.relpath(output_file))
在這個示例中,我們首先使用os.getcwd()函數獲得當前工作目錄,在輸入和輸出路徑中使用os.path.join()函數構造路徑名,使用os.path.exists()函數檢查輸出目錄是否存在(如果不存在,使用os.mkdir()創建目錄)。
最後,我們在文件處理完成時輸出了完成消息,其中使用os.path.relpath()獲得相對路徑。
六、總結
os.path.relpath()是Python的一個非常有用的文件處理函數,用於計算任意兩個路徑之間的相對路徑。這個函數將專門處理路徑和文件名的分隔符,以及在處理不同操作系統的文件路徑時的其他差異。
在使用os.path.relpath()函數時,需要知道起點路徑和目標路徑,通常,起點路徑是當前工作目錄,而目標路徑則是需要進行處理的文件路徑。
原創文章,作者:ZEKW,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/144435.html