Ftplib upload failed on second upload, directory not empty

304 views Asked by At

I'm trying to upload all my files to a time_name directory (such as "170905_161330") in my ftp server.

# -*- coding:utf-8 -*-
import ftplib
import os
import datetime

CWD = os.getcwd()
NOW_STR = str(datetime.datetime.now())
LOCAL_STR = "HDD1/AutoBackUp/" + NOW_STR[2:4]+NOW_STR[5:7]+NOW_STR[8:10]+"_"+NOW_STR[11:13]+NOW_STR[14:16]+NOW_STR[17:19]+"/"

FTP_ADDRESS = 'FTP_ADDRESS'
FTP_ID = '1'
FTP_PW = '1'
ftp = ftplib.FTP(FTP_ADDRESS, FTP_ID, FTP_PW)

for i in os.listdir(CWD):
    FILENAME = str(i)
    print(FILENAME)
    ftp.mkd(LOCAL_STR)

    LOCAL_NAME = LOCAL_STR + FILENAME
    print(str(LOCAL_NAME))
    with open(FILENAME, 'rb') as fileOBJ:
        ftp.storlines('STOR ' + str(LOCAL_NAME), fileOBJ)
ftp.quit()

But the error

ftplib.error_perm: 550 HDD1/AutoBackUp/170905_160635/: Directory not empty

continues to appear, while the first file is uploaded correctly. After that, it doesn't work.

I can check my first file in ftp server, but yeah. second file doesn't exist. I guess... storlines function only works when upload folder is empty.

How can I solve this problem?

1

There are 1 answers

0
Matteo Ragni On BEST ANSWER

From a very rapid read of your code, I suspect that the problem is in ftp.mkd. You already created the directory at the first iteration of the for loop.

To test this error on your local system, open the terminal:

  1. write a mkdir test command
  2. write a mkdir test again
  3. You'll see an error: File Exist. I think the directory not empty is gnerated from this error in the server.

Modify your code to put ftp.mkd before the for loop:

ftp.mkd(LOCAL_STR)
for i in os.listdir(CWD):
    FILENAME = str(i)
    print(FILENAME)

    LOCAL_NAME = LOCAL_STR + FILENAME
    print(str(LOCAL_NAME))
    with open(FILENAME, 'rb') as fileOBJ:
        ftp.storlines('STOR ' + str(LOCAL_NAME), fileOBJ)
ftp.quit()

and test it again. Please remember to remove the directory from the server before testing it.