【问题标题】:Not able to download files from FTP无法从 FTP 下载文件
【发布时间】:2018-08-01 13:59:43
【问题描述】:

我正在尝试使用 python 脚本从我的 ftp 服务器下载文件...但是我得到的文件大小为 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()

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

【问题讨论】:

  • expect: pass 在调试问题时不好用。
  • 我对python很陌生...不知道...感谢@KlausD。但问题依然存在。
  • 不需要给ftp服务器指定端口号吗?n我用的是server = ftplib.FTP() server.connect(<ip address>, <port number>)
  • 也试过@RoadRunner...它仍然下载大小为0kb的文件。
  • 看起来你已经解决了你的问题,因为你已经发布了follow up question。因此,请发布您的解决方案或删除您的问题。

标签: python python-2.7 ftp


【解决方案1】:
   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")

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    • 2014-08-05
    • 1970-01-01
    • 2021-02-02
    • 2021-10-10
    • 1970-01-01
    相关资源
    最近更新 更多