2010-05-24 212 views

回答

24

os.path.splitext()os.rename()

例如:

# renamee is the file getting renamed, pre is the part of file name before extension and ext is current extension 
pre, ext = os.path.splitext(renamee) 
os.rename(renamee, pre + new_extension) 
+0

你能更具體,我看到的文檔之前也沒有工作。 – MysticCodes 2010-05-24 21:17:58

+0

使用第一個函數來獲得基數。將它與新擴展相結合,並將舊文件名和新文件名傳遞給第二個函數。 – 2010-05-24 21:20:28

+6

更正:'os.rename(root,root + new_extension)'應該讀取'os.rename(renamee,root + new_extension)' – mloskot 2014-05-20 10:16:50

44
import os 
thisFile = "mysequence.fasta" 
base = os.path.splitext(thisFile)[0] 
os.rename(thisFile, base + ".aln") 

哪裏thisFile =您正在改變

+5

我更喜歡這個答案,因爲它提供了一個例子,而不僅僅是引用完成任務所需的方法。謝謝@FryDay – sadmicrowave 2013-08-30 03:45:46

11

使用此文件的絕對路徑:

os.path.splitext("name.fasta")[0]+".aln" 

這裏是多麼上述工程:

的splitext方法從擴展創建一個元組分隔名稱:

os.path.splitext("name.fasta") 

創建的元組現在包含字符串「名」和「FASTA」。 然後你只需要訪問字符串「名」,這是元組的第一個元素:

os.path.splitext("name.fasta")[0] 

然後你想要一個新的擴展添加到該名稱:

os.path.splitext("name.fasta")[0]+".aln" 
8

起價Python 3.4裏面有pathlib內置庫。因此,代碼可能是這樣的:

from pathlib import Path 

filename = "mysequence.fasta" 
new_filename = Path(filename).stem + ".aln" 

https://docs.python.org/3.4/library/pathlib.html#pathlib.PurePath.stem

我愛pathlib :)

+0

這是一個非常酷的lib!謝謝! – 2017-04-24 01:06:16

+0

這對於python 3.6字符串插值語法來說更好(https://www.python.org/dev/peps/pep-0498/) 'new_filename = f「{Path(filename).stem} .aln」' – 2018-02-03 07:11:42

+0

小心 - 如果有人存在,莖也會剝離路徑。如果你想重命名文件,並且提供了一個路徑(當然這不是問題),這種技術會失敗。 – 2018-02-11 15:49:11

4

使用pathlib.Path一種優雅的方式:

from pathlib import Path 
p = Path('mysequence.fasta') 
p.rename(p.with_suffix('.aln')) 
+0

雖然OP沒有要求執行重命名,但它是在標籤中,並且如果要執行重命名,並且如果可能輸入可能有路徑而不僅僅是文件名,則此技術是正確的一。 – 2018-02-11 15:51:08