这个最好的答案
您可能希望使用ftp.nlst(),而不是ftp.retrlines()。它会给你你想要的。
如果不能,请阅读以下内容:
系统管理进程的生成器
在他现在著名的评论Generator Tricks For Systems Programmers An Introduction中,David M.Beazley给出了许多receipes来解决这种带有wiick和可重用代码的数据问题。
例如:# empty list that will receive all the log entry
log = []
# we pass a callback function bypass the print_line that would be called by retrlines
# we do that only because we cannot use something better than retrlines
ftp.retrlines('LIST', callback=log.append)
# we use rsplit because it more efficient in our case if we have a big file
files = (line.rsplit(None, 1)[1] for line in log)
# get you file list
files_list = list(files)
为什么不立即生成列表?
好吧,这是因为这样做会给你带来很大的灵活性:你可以在把文件转换成files_list之前应用任何中间生成器来过滤文件:它就像管道,添加一行,添加一个进程而不会过热(因为它是生成器)。如果你摆脱了retrlines,它仍然有效,因为它甚至更好,因为你没有存储列表,哪怕一次。
编辑:好吧,我读到了另一个答案的评论,它说如果名字中有空格的话,这就不起作用了。
酷,这将说明为什么这个方法是方便的。如果你想在这个过程中改变什么,你只要改变一条线。交换:files = (line.rsplit(None, 1)[1] for line in log)
以及# join split the line, get all the item from the field 8 then join them
files = (' '.join(line.split()[8:]) for line in log)
好吧,这在这里可能不明显,但对于大型批处理脚本来说,这很好:-)