Question

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>
Was it helpful?

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)

OTHER TIPS

I know you got an answer but

size = FTP.size(fullpath) FALSE maybe you copied it from https://docs.python.org/2/library/ftplib.html

You see all of the functions have FTP.function() it just a headline

try using

size = ftp.size(fullpath)

am amazed no one pointed that out for almost 3 years

NameError: name 'FTP' is not defined === check the name

I know because I had the same error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top