Python打开FTP url并写入文件

时间:2016-06-29 13:01:38

标签: python python-3.x ftp

如何打开和FTP网址并将其下载到文件中。我正在尝试的东西看起来像这样:

from contextlib import closing
from urllib.request import urlopen

url = 'ftp://whatever.com/file.txt'
target_path = 'file.txt'

with closing(urlopen(url)) as source:
    with open(target_path, 'wb') as target:
        target.write(source)

然而,这失败并出现以下错误:

TypeError: 'addinfourl' does not support the buffer interface

有没有简单的方法让这项工作?特别是如果我想扩展它,以便在下载文件时提取文件?

1 个答案:

答案 0 :(得分:0)

write需要具有缓冲区接口的对象,特别是bytes,但source实际上是BufferedReader(如果是http,则为HTTPResonse。要获取字节,您需要调用BufferedReader.read()

from contextlib import closing
from urllib.request import urlopen

url = 'ftp://whatever.com/file.txt'
target_path = 'file.txt'

with closing(urlopen(url)) as source:
    with open(target_path, 'wb') as target:
        target.write(source.read())