Wednesday, January 15, 2025
HomeProgrammingHow can I delete a file or folder in Python?

How can I delete a file or folder in Python?

In Python, you can delete a file or folder using the os or shutil modules.

  1. To delete a file:
    python
    import os
    os.remove('path_to_file')
  2. To delete an empty folder:
    python
    import os
    os.rmdir('path_to_folder')
  3. To delete a folder with contents:
    python
    import shutil
    shutil.rmtree('path_to_folder')

Make sure you have the necessary permissions to delete the file or folder. Always double-check the path to avoid accidental deletion of important files.

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