无法从FTP下载文件

时间:2018-08-01 13:59:43

标签: python python-2.7 ftp

我正在尝试从ftp服务器上使用python脚本下载文件...但是我得到的文件大小为0 kb ...我无法确切知道我错了...我实际上通过文件名中的特定字符串搜索文件,然后将具有该字符串的所有文件下载到给定目录的ftp中。

这是我的代码:

# Libraries
import re
import os
import ftplib
import ntpath

ftp = ftplib.FTP("192.168.1.786:22")
ftp.login("Marshmellow", "YourPasswordHere")
##ftp.dir("feed_1")

files = []

## F = open('Files.txt','a')

try:
    files = ftp.nlst("feed_1")
    for fname in files:
        res = re.findall("2018-07-25", fname)
        if res:
           # Open the file for writing in binary mode
            print 'Opening local file ' + ntpath.basename(fname)
            file = open(ntpath.basename(fname), 'wb')

            # Download the file a chunk at a time
            # Each chunk is sent to handleDownload
            # We append the chunk to the file and then print a '.' for progress
            # RETR is an FTP command

            print 'Getting ' + ntpath.basename(fname)
            try:
                ftp.retrbinary('RETR ' + ntpath.basename(fname), file.write)
            except:
                pass
            # Clean up time
            print 'Closing file ' + ntpath.basename(fname)
            file.close() 
            print (fname)
##          F.write(fname + '\n')
        if not res:
            continue
except ftplib.error_perm , resp:
    if str(resp) == "550 No files found":
        print "No files in this directory"
        pass
    else:
        raise

## F.close()

如果有人知道这有什么问题,请帮助我。

1 个答案:

答案 0 :(得分:0)

   try:
    ftp.cwd("feed_1") 
    files = ftp.nlst() for fname in files: 
    res = re.findall("2018-07-25", fname) if res: 
    # Open the file for writing in binary mode 
    print 'Opening local file ' + ntpath.basename(fname) 
    file = open(ntpath.basename(fname), 'wb')

我刚刚使用ftp.cwd(“ feed_1”)设置了当前的工作目录,而我以前做错了类似的方法:files = ftp.nlst(“ feed_1”)