简体   繁体   English

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

[英]how to read a file on ftp with python?

here is my code: 这是我的代码:

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()

I think it should be ok, but I got an error 我认为应该没问题,但我收到了一个错误

Traceback (most recent call last):

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

where is the problem? 问题出在哪儿?

You cannot read the remote file using open like local file. 您无法使用本地文件open来读取远程文件。 You need to download the file from the remote host first. 您需要先从远程主机下载文件。

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()

You need to use a_host.open , not a Python default open . 您需要使用a_host.open ,而不是Python默认open

Thus, instead: 因此,相反:

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

This: 这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM