Search code examples
pythonftpfilesize

Using python to find the file size of files on a ftp


I'm new to python and I'm trying to read an ftp directory and write the filenames and file sizes to a file (currently a text file)

import sys
import os
import ftplib
import ftputil
import fnmatch
log = open("C:/..../ftp_name.txt","a")
print "logging into FTP" # print 
host = ftputil.FTPHost('address','Uname','Pass') # ftp host info
recursive = host.walk("/WORLDVIEW",topdown=True,onerror=None) # recursive search 
for root,dirs,files in recursive:
    for name in files:
        fullpath = os.path.join(root, name)
        size = FTP.size(fullpath)
        writepath = fullpath + " " +size + "\n"
        log.write(writepath)

I got it to write the filename and path but once I added the size function in it went wrong

The error I received was:

<b>NameError: name 'FTP' is not defined</b>

I have also tried replacing

size = FTP.size(fullpath)

with

size = recursive.size(fullpath)

which returned the error:

<b>AttributeError: 'generator' object has no attribute 'size'</b>

Solution

  • Generally to get file size you use the os module: https://docs.python.org/2/library/os.path.html#os.path.getsize.

    When using ftputil they make that an equivlant call of host.path.getsize

    You can view more of the documentation for it here: http://mcdc.missouri.edu/libs/python/ftputil/ftputil.html#retrieving-information-about-directories-files-and-links

       ...
       for root,dirs,files in recursive: 
           for name in files: 
               fullpath = host.path.join(root, name)
               size = host.path.getsize(fullpath)