Python os.remove()方法

Python的remove()方法刪除檔路徑。如果路徑是一個目錄,則引發錯誤:OSError

語法

以下是remove()方法的語法 -

os.remove(path)

參數

  • path - 這是要刪除的路徑。

返回值

  • 此方法不返回任何值。

示例

以下示例顯示了remove()方法的用法。

# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")

# listing directories
print ("The dir is: %s" %os.listdir(os.getcwd()))

# removing
os.remove("test.java")

# listing directories after removing path
print ("The dir after removal of path : %s" %os.listdir(os.getcwd()))

編譯並運行上面的程式,將輸出以下結果 -

The dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home',
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files',
   'java.ppt', 'ParallelPortViewer', 'test.java'
]
The dir after removal of path : [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 'home',
   'Java Multiple Inheritance.html', 'Java Multiple Inheritance_files',
   'java.ppt', 'ParallelPortViewer'
]

上一篇: Python os模組方法 下一篇: Python異常處理