Python: getting multiple files from FTP server

[ enter image description here]

I have few problems trying to fetch some files from an FTP server using a Python script. I have searched for this but with no success. This is what I knew:

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 cannot be found inside C:\\backups eindwerk\\omglld\\MonMay81345092017196

.

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

+3


source to share


1 answer


One glaring problem is this:

os.mkdir(maps[i])

      

It will work on the first pass. But later, you will create a subfolder of the previous subfolder. You must use the full path, as in os.chdir

:

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

      



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


Anyway, why are you reinventing the wheel? Use existing solutions for recursive loading:
Loading a directory tree using ftplib .

+1


source







All Articles