利用ftplib创建目录,且若上级目录不存在,就创建上级目录
时间: 2024-05-01 10:16:12 浏览: 12
可以使用以下代码创建目录(若上级目录不存在,就创建上级目录):
```python
import ftplib
def ftp_mkdir_recursive(ftp, path):
# split path into directory and basename
dirname, basename = os.path.split(path)
# if dirname is empty or only a single '/', dirname is the root directory
if dirname in ('', '/'):
return
# if the directory exists, change into it
try:
ftp.cwd(dirname)
except ftplib.error_perm as e:
# if directory does not exist, recursively create it
if e.args[0].startswith('550'):
ftp_mkdir_recursive(ftp, dirname)
ftp.mkd(dirname)
ftp.cwd(dirname)
# create the target directory
try:
ftp.mkd(path)
except ftplib.error_perm as e:
# ignore directory already exists error
if not e.args[0].startswith('550'):
raise
# connect to ftp server
ftp = ftplib.FTP('ftp.your-ftp-server.com')
ftp.login('username', 'password')
# create remote directory
remote_path = '/path/to/new/directory'
ftp_mkdir_recursive(ftp, remote_path)
# disconnect from ftp server
ftp.quit()
```