版權所有,未經許可,禁止轉載
章節
- Python 介紹
- Python 開發環境搭建
- Python 語法
- Python 變量
- Python 數值類型
- Python 類型轉換
- Python 字符串(String)
- Python 運算符
- Python 列表(list)
- Python 元組(Tuple)
- Python 集合(Set)
- Python 字典(Dictionary)
- Python If … Else
- Python While 循環
- Python For 循環
- Python 函數
- Python Lambda
- Python 類與對象
- Python 繼承
- Python 迭代器(Iterator)
- Python 模塊
- Python 日期(Datetime)
- Python JSON
- Python 正則表達式(RegEx)
- Python PIP包管理器
- Python 異常處理(Try…Except)
- Python 打開文件(File Open)
- Python 讀文件
- Python 寫文件
- Python 刪除文件與文件夾
刪除文件
要刪除一個文件,需導入OS模塊,使用其中的os.remove()
函數:
示例
刪除文件“test.txt”:
import os
os.remove("test.txt")
檢查文件是否存在
為了避免出錯,需要在刪除之前檢查文件是否存在:
示例
刪除前檢查文件是否存在:
import os
if os.path.exists("test.txt"):
os.remove("test.txt")
else:
print("文件不存在")
刪除文件夾
要刪除整個文件夾,使用os.rmdir()
方法:
示例
刪除文件夾“testfolder”:
import os
os.rmdir("testfolder")
注意: 只能刪除空文件夾。