【问题标题】:Downloading file from FTP server with ftplib: Always 0 bytes/empty使用 ftplib 从 FTP 服务器下载文件:始终为 0 字节/空
【发布时间】:2021-04-16 16:12:37
【问题描述】:

我正在尝试使用 Python ftplib 从 FTPS 服务器下载文件。

但下载的文件总是有 0 个字节(为空)。 如果我使用 WinSCP 在服务器中看到该文件,则该文件有数据(大约 1Kb)。 在 WinSCP 中,我使用选项 "Encryption: Explicit TSL""PassiveMode=False"

代码有什么问题? 谢谢!!

这是我正在使用的代码:

import ftplib

server='10.XX.XX.XX'
username='username'
password='password'

session = ftplib.FTP_TLS(server)
session.login(user=username,passwd=password)
session.prot_p()
session.set_pasv(False)
session.nlst()
session.cwd("home")
print(session.pwd())
filename = "test.txt"
# Open a local file to store the downloaded file
my_file = open(r'c:\temp\ftpTest.txt', 'wb') 
session.retrbinary('RETR ' + filename, my_file.write, 1024)

session.quit()

【问题讨论】:

    标签: python python-3.x ftp ftplib


    【解决方案1】:

    下载后您没有关闭本地文件。您应该为此使用上下文管理器。同样对于 FTP 会话:

    with ftplib.FTP_TLS(server) as session:
        session.login(user=username, passwd=password)
        session.prot_p()
        session.set_pasv(False)
        session.nlst()
        session.cwd("home")
        print(session.pwd())
        filename = "test.txt"
        # Open a local file to store the downloaded file
        with open(r'c:\temp\ftpTest.txt', 'wb') as my_file: 
            session.retrbinary('RETR ' + filename, my_file.write, 1024)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多