python 檔案路徑名,檔名,字尾名的操作

2022-03-15 15:17:32 字數 965 閱讀 4478

需要使用路徑名來獲取檔名,目錄名,絕對路徑等等。

使用os.path 模組中的函式來操作路徑名。下面是乙個互動式例子來演示一些關鍵的特性:

>>> import os

>>> path = '/users/beazley/data/data.csv'

>>> # get the last component of the path

>>> os.path.basename(path)

'data.csv'

>>> # get the directory name

>>> os.path.dirname(path)

'/users/beazley/data'

>>> # join path components together

>>> os.path.join('tmp', 'data', os.path.basename(path))

'tmp/data/data.csv'

>>> # expand the user's home directory

>>> path = '~/data/data.csv'

>>> os.path.expanduser(path)

'/users/beazley/data/data.csv'

>>> # split the file extension

>>> os.path.splitext(path)

('~/data/data', '.csv')

>>>

對於任何的檔名的操作,你都應該使用os.path 模組,而不是使用標準字串操作來構造自己的**。特別是為了可移植性考慮的時候更應如此,因為os.path 模組知道unix 和windows 系統之間的差異並且能夠可靠地處理類似data/data.csv 和datandata.csv 這樣的檔名。其次,你真的不應該浪費時間去重複造輪子。通常最好是直接使用已經為你準備好的功能。

Python 獲取路徑名和檔名

os.path.dirname 和os.path.abspath 的區別 dirname是獲取的檔案所在目錄的路徑 abspath是獲取的檔案的絕對路徑 但是,當dirname括號內是相對路徑的時候,他返回是空,什麼都沒有 而如果abspath執行的話,如果檔案在當前目錄下有,他就返回,如果沒有,他...

linux c下,從路徑名中分離檔名

首先介紹一些查詢字元的函式 標頭檔案 include strrchr 函式用於查詢某字元在字串中最後一次出現的位置,其原型為 char strrchr const char str,int c 引數 str 為要查詢的字串,c 為要查詢的字元。strrchr 將會找出 str 字串中最後一次出現的字...

獲取模組檔案路徑名

獲取模組檔案路徑名 static bool getmodulepathname cstdstring strmodulepathname zeromemory szdrive,sizeof szdrive zeromemory szdir,sizeof szdir zeromemory szfile...