深度阅读

How can I delete a file or folder in Python?

作者
作者
2023年08月22日
更新时间
10.8 分钟
阅读时间
0
阅读量

To delete a file or folder in Python, you can use the functions provided in the os and shutil modules.

For deleting a file, you can use the os.remove() or os.unlink() function. Here is an example:

import os

if os.path.exists("file.txt"):
  os.remove("file.txt")

For deleting an empty directory, you can use the os.rmdir() function. Here is an example:

import os

if os.path.exists("my_folder"):
  os.rmdir("my_folder")

If you want to delete a directory and all its contents (whether it is empty or not), you can use the shutil.rmtree() function. Here is an example:

import shutil

if os.path.exists("my_folder"):
  shutil.rmtree("my_folder")

Note that when using rmtree(), you should make sure that you want to delete the entire directory and all its contents, since the deletion is permanent and cannot be undone.

Also, before attempting to delete a file or folder, make sure that they exist by using the os.path.exists() function. This helps to prevent errors if you try to delete a file or folder that does not exist.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。