Python 獲取檔案的檔名和字尾名(副檔名)

2021-10-08 10:50:42 字數 547 閱讀 3513

我們可以使用os.path.splitext(file)[0]獲得檔名。

我們可以使用os.path.splitext(file)[-1]獲得以.為開頭的檔案字尾名。

接下來我們看乙個例子:

import os

file

="hello world.py"

# 獲取字首(檔名稱)

print

(os.path.splitext(

file)[

0])# 獲取字尾(檔案型別)

print

(os.path.splitext(

file)[

-1])

print

(os.path.splitext(

file)[

-1][

1:])

----

---執行結果---

----

-hello world

.pypy

Python 獲取資料夾下的檔名

os 模組下有兩個函式 os.walk os.listdir 模組os中的walk 函式可以遍歷資料夾下所有的檔案。os.walk top,topdown ture,onerror none followlinks false 該函式可以得到乙個三元元組 tupple dirpath,dirname...

獲取檔名和副檔名

string afirstname afile.substring afile.lastindexof 1,afile.lastindexof afile.lastindexof 1 檔名 string alastname afile.substring afile.lastindexof 1,af...

獲取檔名的方式

一 directory類 按照萬用字元搜尋目錄下的檔案 string directory.getfiles string path,string searchpattern,searchoption searchoption path 目錄 searchpattern 萬用字元 searchopti...