【问题标题】:Files are corrupted after transfer them to a FTP server using ftplib使用 ftplib 将文件传输到 FTP 服务器后文件损坏
【发布时间】:2016-08-21 21:29:46
【问题描述】:

我在上传 .gz 文件时遇到了 ftplib 库问题。

该脚本以前可以运行,但不知何故,在我的数千个版本之一中,我更改了一些导致传输损坏文件的内容。 文件已成功传输到 ftp 服务器,但在 ftp 中使用的文件已损坏,无法打开。

要传输的文件没有任何问题。此外,如果文件未压缩,则传输没有任何问题。这与它读取 .gz 的方式有关

谁能告诉我代码有什么问题?

for filename in dir:

    os.system("gzip %s/%s" % (Path, filename))
    time.sleep(5)  # Wait up to 4 seconds to compress file
    zip_filename = filename + '.gz'

    try:
        # Connect to the host
        ftp = ftplib.FTP(host)
        # Login to the ftp server
        ftp.login(username, password)

        # Transfer the file
        myfile = open(zip_filename, 'rb')
        ftp.storlines("STOR temp/" + zip_filename, myfile)
        myfile.close()

    except ftplib.all_errors as e:
        print(e)

【问题讨论】:

  • 顺便说一句,你不应该在gzip之后等待任何事情; os.system 是同步的 - 当它返回时,gzip 已经完成。

标签: python ftp ftplib


【解决方案1】:

问题在于 storlines 的使用。在这种情况下,需要使用 storbinary

【讨论】: