【问题标题】:how to read a file on ftp with python?如何用python读取ftp上的文件?
【发布时间】:2015-10-23 22:30:13
【问题描述】:

这是我的代码:

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'

问题出在哪里?

【问题讨论】:

标签: python ftp


【解决方案1】:

您无法像本地文件一样使用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()

【讨论】:

    【解决方案2】:

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

    因此,改为:

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

    这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 2015-06-13
      • 2021-11-22
      • 1970-01-01
      • 2013-09-17
      • 2020-01-16
      • 1970-01-01
      相关资源
      最近更新 更多