Python os.remove()方法

2019-10-16 23:05:00

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'
]