python 判断ftp是否存在目录,若不存在则ftp远程创建一个或者层级目录
时间: 2023-08-02 14:20:48 浏览: 212
可以使用 Python 的 ftplib 库来实现判断是否存在目录,并在不存在目录时创建一个或者多个层级目录的功能。具体步骤如下:
1. 连接 FTP 服务器:
```python
from ftplib import FTP
ftp = FTP(host, user, password)
```
2. 判断目录是否存在,可以使用 `nlst` 方法获取当前目录下的所有文件和目录列表,并判断需要的目录是否存在:
```python
def is_ftp_dir_exists(ftp, remote_path):
file_list = []
try:
ftp.retrlines('LIST ' + remote_path, file_list.append)
except Exception as e:
print(e)
return False
for file in file_list:
if file.split()[-1] == remote_path.split('/')[-1]:
return True
return False
```
3. 如果目录不存在,则使用 `mkd` 方法逐层创建目录:
```python
def ftp_mkdir_recursive(ftp, remote_path):
if is_ftp_dir_exists(ftp, remote_path):
return True
else:
parent_dir = remote_path[:remote_path.rfind('/')]
if ftp_mkdir_recursive(ftp, parent_dir):
try:
ftp.mkd(remote_path)
return True
except Exception as e:
print(e)
return False
else:
return False
```
完整代码示例:
```python
from ftplib import FTP
host = 'ftp.example.com'
user = 'username'
password = 'password'
remote_path = '/remote/path/to/directory'
ftp = FTP(host, user, password)
def is_ftp_dir_exists(ftp, remote_path):
file_list = []
try:
ftp.retrlines('LIST ' + remote_path, file_list.append)
except Exception as e:
print(e)
return False
for file in file_list:
if file.split()[-1] == remote_path.split('/')[-1]:
return True
return False
def ftp_mkdir_recursive(ftp, remote_path):
if is_ftp_dir_exists(ftp, remote_path):
return True
else:
parent_dir = remote_path[:remote_path.rfind('/')]
if ftp_mkdir_recursive(ftp, parent_dir):
try:
ftp.mkd(remote_path)
return True
except Exception as e:
print(e)
return False
else:
return False
if ftp_mkdir_recursive(ftp, remote_path):
print('目录创建成功!')
else:
print('目录创建失败!')
ftp.quit()
```
注意:FTP 服务器需要有创建目录的权限。
阅读全文
相关推荐


















