【问题标题】:Downloading files from ftp server using python but files not opening after downloading使用python从ftp服务器下载文件但下载后文件未打开
【发布时间】:2020-04-03 08:49:02
【问题描述】:

我正在使用 python 从 ftp 服务器下载文件,我可以下载文件,但是当我打开文件时,它们似乎已损坏或无法打开 歌曲或 jpg 等文件可以正常工作,但文档、excel 表格、pdf 和文本文件无法正常下载。

以下是我的代码:

from ftplib import FTP
ftp = FTP()
ftp.connect(ip_address,port)
ftp.login(userid,password)
direc='directory path'
ftp.cwd(direc)
doc='doc.txt' or xlsx or pdf or jpg etc
download_path='path to download file on desktop'
file=open(download_path+ doc,'wb')
ftp.retrbinary(f"RETR {doc}", file.write)

我能够下载所需的文件,但其中大部分都需要损坏。 我应该进行哪些更改才能使代码正常工作。

【问题讨论】:

标签: python ftplib


【解决方案1】:

目前无法测试 FTP,但我看到的是您的文件打开而不是关闭的问题。

选项 A:

file=open(download_path + doc,'wb')  # add '+' to append instead of overwriting
...
...
file.close()

选项 B(上下文管理器,在您完成后关闭文件时很有用):

with open(download_path + doc,'wb') as file:
    file.write(*args, **kwargs)

关于模块ftplib的使用,stevehaftp.retrbinary() help python下面的帖子回复很好。

关于使用上下文管理器打开和写入文件,请参见 sir-snoopalot 引用的 How to open a file using the open with statementhandling exceptions (Python 3 documentation)

还要查看ftplib 模块文档以获得进一步说明。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我没有尝试过你的代码,但是查看 Python 文档你可能忘记关闭文件并正确退出,所以文件缓冲区可能没有完全写入磁盘。

    试试这个:

    with open(download_path+ doc,'wb') as fp:
        ftp.retrbinary(f"RETR {doc}", file.write)
    
    ftp.quit()
    

    with语句会在退出这个block时对文件执行close函数

    【讨论】:

    • 你能告诉我如何下载整个文件夹而不是一个文件
    【解决方案3】:

    您忘记关闭文件。只需在代码末尾添加以下内容即可。

    file.close()
    

    【讨论】:

      最近更新 更多