Search code examples
pythonftpglobal-variablesnameerror

NameError: name 'ftp' is not defined, Python


I am getting this error even though I declared ftp.

Here is the complete error message:

File "./sFTPscript.py", line 173, in <module> main()
File "./sFTPscript.py", line 167, in main uploadFTP()
File "./sFTPscript.py", line 33, in uploadFTP ftp.pwd()

NameError: name 'ftp' is not defined

--

from ftplib import FTP
import os
import sys
import kunden.config as config


def connFTP():
ftp = FTP(config.host)
ftp.login(config.username,config.password)
print("connected")

def uploadFTP():
os.chdir(config.localpath)
ftp.pwd()
ftp.cwd('test')
list_local = os.listdir(config.localpath)
for file in list_local:
    ftp.storbinary('STOR '+file, open(file,'rb'))

return list_local

def main():

    connFTP()
    uploadFTP()

if __name__ == '__main__':
    main()

I tried to make ftp a global variable before it get used but still the same error


Solution

  • ftp is not known within the scope of uploadFTP(). Either use a class, a global variable (use global ftp) or pass the object around. The latter could be:

    def connFTP():
        ftp = FTP(config.host)
        ftp.login(config.username,config.password)
        print("connected")
        return ftp
        #      ^^^
    
    def uploadFTP(ftp=None):
        os.chdir(config.localpath)
        ftp.pwd()
        ftp.cwd('test')
        list_local = os.listdir(config.localpath)
        for file in list_local:
            ftp.storbinary('STOR '+file, open(file,'rb'))
        
        return list_local
    
    def main():
    
        ftp = connFTP()
        uploadFTP(ftp)
        #         ^^^
    
    if __name__ == '__main__':
        main()
    

    Also, you do not do anything with the returned list_local from uploadFTP() (yet?).