python删除FTP目录实例
时间: 2024-11-25 14:18:23 浏览: 8
python FTP批量下载/删除/上传实例
在Python中,我们可以使用ftplib模块来删除FTP服务器上的目录。以下是一个简单的例子,展示了如何连接到FTP服务器,切换到需要删除的目录,并删除它:
```python
import ftplib
def delete_ftp_directory(host, username, password, directory_path):
# 创建FTP对象
ftp = ftplib.FTP(host)
# 登录FTP服务器
ftp.login(user=username, passwd=password)
# 进入目录
try:
ftp.cwd(directory_path) # 切换到要删除的目录
except ftplib.error_perm as e:
print(f"Directory '{directory_path}' does not exist or you don't have permission to access it.")
return
# 删除目录(如果为空)
if ftp.pwd() == directory_path: # 确保当前目录就是待删除的目录
try:
ftp.rmd(directory_path) # 使用rmdir删除空目录
print(f"Directory '{directory_path}' has been successfully deleted.")
except ftplib.error_perm as e:
print(f"Failed to delete directory '{directory_path}'. Error: {e}")
# 关闭FTP连接
ftp.quit()
# 调用函数并传递服务器信息
delete_ftp_directory("your_server_address", "your_username", "your_password", "/path/to/directory")
```
请注意,在实际操作中,你需要将`host`, `username`, `password`以及`directory_path`替换为你具体的FTP服务器配置。
阅读全文