gyula
gyula

Reputation: 257

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?

Upvotes: 2

Views: 12592

Answers (2)

m0nhawk
m0nhawk

Reputation: 24300

You need to use a_host.open, not a Python default open.

Thus, instead:

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

This:

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

Upvotes: 1

falsetru
falsetru

Reputation: 369464

You cannot read the remote file using open like local file. 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()

Upvotes: 5

Related Questions