Python FTP Client. Force unique filenames on download

203
November 25, 2017, at 1:55 PM

I have the following ftp client:

import ftplib
def downloadFTP(file_name):
    ftp = ftplib.FTP()
    ftp.connect(host, port)
    ftp.login()
    local_file = file_name
    try:
        ftp.retrbinary("RETR " + file_name ,open(local_file, 'wb').write)
    except ConnectionRefusedError:
        ftp.quit()
        return
    ftp.quit()

When I download a file from the server that already exists locally, the local copy is overwritten. What I would like to happen instead is that a new copy with a unique name is created instead. I wrote my own function that does this:

    if os.path.isfile(local_file):        
        x = 1
        while os.path.isfile(os.path.splitext(local_file)[0] + " (" + str(x) + ")" + os.path.splitext(local_file)[1]):
            x += 1
        local_file = os.path.isfile(os.path.splitext(local_file)[0] + " (" + str(x) + ")" + os.path.splitext(local_file)[1])
    return local_file

But I've made assumptions that I don't trust to be true in a production environment, and it seems ridiculous to reinvent the wheel when it's been written so many times before.

Is there some cross-platform way to invoke the operating system's file naming procedure? For example in Ubuntu, if I paste the same file multiple times into the same directory, I get the following:

test.txt
test (copy).txt
test (another copy).txt
test (3rd copy).txt
test (4th copy).txt
... etc
READ ALSO
Counting PDF pages within subdirectories (using python or cmd if possible, but not necessary)

Counting PDF pages within subdirectories (using python or cmd if possible, but not necessary)

Just wondering if there might be a bit of code out there to help out with thisI'll lay this out quickly: Suppose I'm looking at the directory "Pressure on Beacon"

170
Keeping ports open in a python script that is run continuously

Keeping ports open in a python script that is run continuously

I'm trying to develop a server script using python 34 that runs perpetually and responds to client requests on up to 5 separate ports

186
Parsing JSON in a webhook

Parsing JSON in a webhook

I have a url I want to POST some JSON data to, but I'm having trouble decoding the dataI'm using Postman to test sending data to the webhook, and I've set up a system to capture what the webhook receives

191