Search code examples
pythonpython-3.xftpbackupftplib

Python: retrieving multiple files from an FTP server


[enter image description here]

I have little problem when trying to get some files from an FTP server using a Python script. I've searched for this, but without success. This is what I have known:

session2.cwd("/archive")
maps = session2.nlst()
opslagplaats = input("waar wil je de backup opslaan?")
backupnaam = input("hoe wil je de backup noemen?")
if opslagplaats == "":
    opslagplaats = "C:\\backups eindwerk"
os.chdir(opslagplaats)
os.mkdir(backupnaam)
os.chdir(opslagplaats + "\\" + backupnaam)
for i in range(len(maps)):
    session2.cwd("/archive/" + maps[i])
    os.mkdir(maps[i])
    os.chdir(opslagplaats + "\\" + backupnaam + "\\" + maps[i])
    files = session2.nlst()
    for j in range(len(files)):
        file = open(files[j], "wb")
        session2.retrbinary("RETR " + files[j], file.write)

And when I try to run this code, it tells me that the given file can't be found inside C:\\backups eindwerk\\omglld\\MonMay81345092017196.

This is how the files are located on the FTP server, and I want to copy/backup them to local place on my PC.


Solution

  • One clear problem is this:

    os.mkdir(maps[i])
    

    It will work on the first pass. But on later, you will be creating a subfolder of the previous subfolder. You must be using a full path, like in the os.chdir:

    os.mkdir(opslagplaats + "\\" + backupnaam + "\\" + maps[i])
    

    (or pop out of subfolder at the end of the loop).


    Anyway, why do you reinvent the wheel? Use existing solutions for recursive download:
    Downloading a directory tree with ftplib.