1. 使用`os.remove()`函数:
import os
file_path = 'example.txt'
if os.path.exists(file_path):
os.remove(file_path)
print('文件已被删除。')
else:
print('文件不存在,无法删除。')
2. 使用`os.unlink()`函数:
import os
file_path = 'example.txt'
if os.path.exists(file_path):
os.unlink(file_path)
print('文件已被删除。')
else:
print('文件不存在,无法删除。')
3. 使用`pathlib.Path.unlink()`方法(适用于Python 3.4及以上版本):
from pathlib import Path
file_path = Path('example.txt')
if file_path.exists():
file_path.unlink()
print('文件已被删除。')
else:
print('文件不存在,无法删除。')
请确保在尝试删除文件之前检查文件是否存在,以避免出现错误。如果需要删除整个文件夹及其内容,可以使用`shutil.rmtree()`函数:
import shutil
directory_path = 'example_directory'
if os.path.exists(directory_path):
shutil.rmtree(directory_path)
print('文件夹已被删除。')
else:
print('文件夹不存在,无法删除。')