Home>

I want to create a directory on the ftp server from the client side and transfer the file.
From directory creation to file transfer is now possible, but the directory with the same name is
An error will occur in some cases, so if there is a directory with the same name,
If there is, delete it before creating the directory.

If there is no directory with the same name, it works without error, but
If there is a directory with the same name, an error will occur.
Therefore, it is considered that the if part is not working.
How will the if part move?

Error message
Traceback (most recent call last):
  File "test.py", line 72, in<module>
    main ()
  File "test.py", line 64, in main
    ftp_upload (hostname, username, password, upload_file, dir)
  File "test.py", line 44, in ftp_upload
    ftp.mkd (dir)
  File "C: \ Python27 \ lib \ ftplib.py", line 589, in mkd
    resp = self.sendcmd ('MKD' + dirname)
  File "C: \ Python27 \ lib \ ftplib.py", line 251, in sendcmd
    return self.getresp ()
  File "C: \ Python27 \ lib \ ftplib.py", line 226, in getresp
    raise error_perm, resp
ftplib.error_perm: 550 Cannot create a file when that file already exists.
Applicable source code
#-*-coding: utf8-*
import ftplib
import os.path
def ftp_upload (hostname, username, password, upload_file, dir):
    ftp = ftplib.FTP (hostname)
    ftp.set_pasv ("true")
    ftp.login (username, password)
    fp = open (upload_file, 'rb')
    if os.path.exists (dir):
        ftp.delete (dir + '/' + upload_file)
        ftp.rmd (dir)
    ftp.mkd (dir)
    s = dir + '/' + upload_file
    ftp.storbinary ('STOR' + s, fp)
    ftp.close ()
    fp.close ()
def main ():
    hostname = "***. ***. **. **"
    upload_file = "test.py"
    username = "hoge"
    password = "hoge"
    dir = "hogehoge"
    ftp_upload (hostname, username, password, upload_file, dir)
if __name__ == '__main__':
    main ()
Supplemental information (FW/tool version etc.)

I use python2.7 on windows.