I am trying to put this into def statments:
#!/usr/bin/env python
import ftplib
import os
import sys
import paramiko
import datetime
import pickle
username = "ftp1"
password = "pass"
try:
try:
print "Connecting to 0.0.0.0"
ftp = ftplib.FTP("0.0.0.0")
ftp.login(username, password)
ftp.cwd('Dir')
except ftplib.all_errors as e:
print(e)
except ftp.login as s:
print (s)
files = []
try:
files = ftp.nlst()
except ftplib.error_perm, resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
----------------------revised--------------------------
#!/usr/bin/env python
import ftplib
import os
import sys
import paramiko
import datetime
import pickle
import ftplib as ftp
hostname = "0.0.0.0"
password = "pass"
username = "ftp1"
def connect():
try:
print "Connecting to 0.0.0.0"
ftp = ftplib.FTP("0.0.0.0")
ftp.login(username, password)
except ftplib.all_errors as e:
print(e)
connect()
def list_files():
files = []
try:
files = ftp.nlst()
except ftplib.error_perm, resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
list_files()
Successful with the first function created:
def connect():
try:
print "Connecting to 0.0.0.0"
ftp = ftplib.FTP("0.0.0.0")
ftp.login(username, password)
except ftplib.all_errors as e:
print(e)
connect()
-----------------------get error on second def statement----------------
def list_files():
files = []
try:
files = ftp.nlst()
except ftplib.error_perm, resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
list_files()
====================AttributeError: 'module' object has no attribute 'nlst'============
Please help me understand what I am missing here.... I am sure it is something simple.... but I am missing it....
Wanna Thank Everyone who posted an Answer to help me correct my mistakes. Was able to figure out what "Arkanosis" was suggesting to fix the errors:
One option you have is to make connect return the ftp variable and then pass it as a parameter to the list_files function. Usage would then look like ftp = connect() then list_files(ftp). Another approach would be to put both functions in a class which would have ftp as an attribute. – Arkanosis
ftp = ftplib.FTP("0.0.0.0")
ftp.login(username,password)
Added ftp to each individual "def" block as such:
I will be converting this to a class statement in the upcoming revisions and will update the post for those who would like use this as template to help build their ftp project.
This is just very basic build to begin communicating with your FTP server as you build your final FTP script.