【问题标题】:Script reading files in ftp directory but not downloading them脚本读取 ftp 目录中的文件但不下载它们
【发布时间】:2017-08-06 18:54:59
【问题描述】:

下面的脚本能够读取 ftp 目录文件中的文件,但它不会下载它们。我知道他们会阅读它们,因为命令窗口中的输出列表会显示它们。

from ftplib import FTP
import os, sys, os.path

def handleDownload(block):
    file.write(block)

ddir='U:/Test Folder'
os.chdir(ddir)
ftp = FTP('sidads.colorado.edu')
ftp.login()

print ('Logging in.')
directory = '/pub/DATASETS/NOAA/G02158/unmasked/2012/04_Apr/'

print ('Changing to ' + directory)
ftp.cwd(directory)
ftp.retrlines('LIST')

print ('Accessing files')

for subdir, dirs, files in os.walk(directory):
     for file in files:
        full_fname = os.path.join(root, fname);
        print ('Opening local file ')
         ftp.retrbinary('RETR U:/Test Folder' + fname,
                       handleDownload,
                       open(full_fname, 'wb'));
         print ('Closing file ' + filename)
         file.close();
ftp.close()

【问题讨论】:

  • 对不起,但 1 个缩进不正确,并且 2)您正在对 file 执行 file.close() 这是一个字符串对象,并且 3)您正在列出本地文件并写入内容在它的远程文件?所以在服务器上下载同名文件之前,您的本地文件必须存在?这不合逻辑。

标签: python python-2.7 python-3.x download ftp


【解决方案1】:

这是您可以使用pysftp 库执行此操作的一种方法:

import pysftp

with pysftp.Connection('hostname', username='username', password='password') as sftp:
    ftp_files = sftp.listdir('/ftp/dir/')

    for file in ftp_files:
        sftp.get(os.path.join('/ftp/dir/', file), localpath=os.path.join('/path/to/save/file/locally/', file))

【讨论】:

    猜你喜欢
    • 2018-07-18
    • 2011-02-16
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    相关资源
    最近更新 更多