Get Ftp.retrlines To Print A File's Content To A String
I want to get the contents of a file with ftplib and store it in a string variable in python. My first attempt is below. I guess lambdas can't contain assignment -- maybe because a
Solution 1:
Firstly, this fails because python does not allow statements inside lambdas, only pure expressions.
Secondly, even if you did this as a function, i,e.:
contents = ""
def assign(s):
contents=s
ftp.retrlines("RETR " + filename, assign )
it would fail, because by running contents=s
you are just creating a local variable, not referencing the (global) variable contents
.
You could further correct it as such:
contents = ""defassign(s):
global contents
contents=s
ftp.retrlines("RETR " + filename, assign )
But this (using globals) is generally considered a bad practice. Instead, you should probably rethink your callback to actually do everything you need to do with the data. This is not always easy; you may want to keep functools.partial
in a handy place in your programming belt.
Solution 2:
outStr = StringIO.StringIO() # Use a string like a file.
ftp.retrlines('RETR ' + fileToGet, outStr.write)
print outStr.getvalue()
outStr.close()
Post a Comment for "Get Ftp.retrlines To Print A File's Content To A String"