[Tutor] ftp recursive directory function doesn't work.
Cameron Simpson
cs at cskk.id.au
Wed Dec 14 04:50:11 EST 2022
On 14Dec2022 19:47, mhysnm1964 at gmail.com <mhysnm1964 at gmail.com> wrote:
>I am trying to navigate a ftp server directory structure to see how big
>the
>directory actually is. The function recursively goes through the
>directories. When I pass the first if test calling the os object. I get a
>file not found error and it breaks. Everything in the first level directory
>are directories. I cannot work out what is going wrong.
[...]
>from ftplib import FTP
>import os
>
>def get_size(ftp, directory):
> size = 0
> ftp.cwd(directory) <ftp://ftp.cwd(directory)>
> files = ftp.nlst(b <ftp://ftp.nlst(b> )
> for file in files:
> if os.path.isdir(file):
> size += get_size(ftp, file)
> else:
> size += ftp.size(file) <ftp://ftp.size(file)>
> return size
Ignoring syntax errors above, the `os.path.isdir` call checks `file` in
the local filesystem, not on the FTP server's file system.
I don't see a method in the `ftplib` module to check whether a remote
path is a directory, but you could try `ftp.cwd(file)` for each name. If
that succeeds it should be a directory, and if it fails you could
assumes it is a file. I haven't tried this.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list