如何使用 python 读取 ftp 上的文件?

how to read a file on ftp with python?

这是我的代码:

import ftputil
import urllib2
a_host = ftputil.FTPHost(hostname, username,passw)

for (dirname, subdirs, files) in a_host.walk("/"): # directory
    for f in files:
            if f.endswith('txt'):
                htmlfile = open(f, 'r')
                readfile = htmlfile.read()

我觉得应该没问题,但是我出错了

Traceback (most recent call last):

    htmlfile = open(f, 'r')
IOError: [Errno 2] No such file or directory: u'readme.txt'

问题出在哪里?

您不能像本地文件一样使用open读取远程文件。您需要先从远程主机下载文件。

for (dirname, subdirs, files) in a_host.walk("/"): # directory
    for f in files:
        if f.endswith('txt'):
            a_host.download(f, f)  # Download first
            with open(f) as txtfile:
                content = txtfile.read()

您需要使用 a_host.open,而不是 Python 默认值 open

因此,改为:

htmlfile = open(f, 'r')
readfile = htmlfile.read()

这个:

htmlfile = a_host.open(f, 'r')
readfile = htmlfile.read()