問題描述
我正在嘗試使用 Python 的 ftplib 讀取文件而不寫入它們.大致相當于:
I am trying to read files using Python's ftplib without writing them. Something roughly equivalent to:
def get_page(url):
try:
return urllib.urlopen(url).read()
except:
return ""
但使用 FTP.
我試過了:
def get_page(path):
try:
ftp = FTP('ftp.site.com', 'anonymous', 'passwd')
return ftp.retrbinary('RETR '+path, open('page').read())
except:
return ''
但這不起作用.文檔中的唯一示例涉及使用 ftp.retrbinary('RETR README', open('README', 'wb').write)
格式編寫文件.是否可以不先寫入就讀取ftp文件?
but this doesn't work. The only examples in the docs involve writing files using the ftp.retrbinary('RETR README', open('README', 'wb').write)
format. Is it possible to read ftp files without writing first?
推薦答案
好吧,答案就在眼前:FTP.retrbinary
方法接受作為第二個參數的函數引用每當從 FTP 連接檢索文件內容時都會調用它.
Well, you have the answer right in front of you: The FTP.retrbinary
method accepts as second parameter a reference to a function that is called whenever file content is retrieved from the FTP connection.
這是一個簡單的例子:
#!/usr/bin/env python
from ftplib import FTP
def writeFunc(s):
print "Read: " + s
ftp = FTP('ftp.kernel.org')
ftp.login()
ftp.retrbinary('RETR /pub/README_ABOUT_BZ2_FILES', writeFunc)
你應該實現 writeFunc
以便它實際上將讀取的數據附加到一個內部變量,就像這樣,它使用一個可調用的對象:
You should implement writeFunc
so that it actually appends the data read to an internal variable, something like this, which uses a callable object:
#!/usr/bin/env python
from ftplib import FTP
class Reader:
def __init__(self):
self.data = ""
def __call__(self,s):
self.data += s
ftp = FTP('ftp.kernel.org')
ftp.login()
r = Reader()
ftp.retrbinary('RETR /pub/README_ABOUT_BZ2_FILES', r)
print r.data
更新:我意識到 Python 標準庫中有一個模塊專門用于此類事情,BytesIO
:
Update: I realized that there is a module in the Python standard library that is meant for this kind of things, BytesIO
:
#!/usr/bin/env python
from ftplib import FTP
from io import BytesIO
ftp = FTP('ftp.kernel.org')
ftp.login()
r = BytesIO()
ftp.retrbinary('RETR /pub/README_ABOUT_BZ2_FILES', r.write)
print r.getvalue()
這篇關于是否可以在不使用 Python 編寫的情況下讀取 FTP 文件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!