本文介绍了获取ftp.retrlines以将文件内容打印为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用ftplib获取文件的内容,并将其存储在python中的字符串变量中.我的第一次尝试是在下面.我猜lambda不能包含赋值-也许是因为lambda是一个函数+变量,它们应该是自包含的(?).
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 lambda is a function + variables that should be self contained (?).
contents = ""
ftp.retrlines("RETR " + filename, lambda s: contents=s) #lambda cannot contain assignment
无论如何,我需要将输出捕获到stdout还是有更简单的方法?
Anyway, do I need to capture output to stdout or is there an easier way?
推荐答案
outStr = StringIO.StringIO() # Use a string like a file.
ftp.retrlines('RETR ' + fileToGet, outStr.write)
print outStr.getvalue()
outStr.close()
https://docs.python.org/2/library/stringio.html
这篇关于获取ftp.retrlines以将文件内容打印为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!