Monday, January 6, 2025
HomeTechHow can I delete a file or folder in Python?

How can I delete a file or folder in Python?

In Python, you can delete files or folders using the os and shutil modules.

1. Deleting a File

To delete a file, use os.remove() or pathlib.Path.unlink().

python
import os
os.remove('file.txt')

2. Deleting an Empty Folder

To delete an empty folder, use os.rmdir().

python
import os
os.rmdir('folder')

3. Deleting a Folder and Its Contents

To delete a folder along with its contents, use shutil.rmtree().

python
import shutil
shutil.rmtree('folder')

4. Using pathlib for Folder Deletion (Python 3.4+)

For deleting empty folders, you can also use pathlib.Path.rmdir().

python
from pathlib import Path
Path('folder').rmdir()
  • Note: Ensure the file or folder is not in use before attempting to delete it.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x