在Python中,删除目录中的文件可以通过`os`模块和`shutil`模块实现。以下是两种常见的方法:
1. 使用`os.remove()`删除单个文件:
import os
def delete_file(file_path):
try:
os.remove(file_path)
print(f"文件 {file_path} 已被删除。")
except OSError as e:
print(f"删除文件时发生错误:{e}")
2. 使用`shutil.rmtree()`递归删除目录及其所有内容:
import shutil
def delete_directory(directory_path):
try:
shutil.rmtree(directory_path)
print(f"目录 {directory_path} 已被删除。")
except OSError as e:
print(f"删除目录时发生错误:{e}")
使用这些函数时,请确保你完全理解它们的作用,并且谨慎操作,因为删除操作是不可逆的。如果你需要删除一个目录及其所有内容,请使用`shutil.rmtree()`。如果你只想删除目录中的文件,请使用`os.remove()`。
请根据你的具体需求选择合适的方法,并确保你提供了正确的文件或目录路径。