使用 python 从 ftp 服务器下载文件,但下载后文件无法打开
Downloading files from ftp server using python but files not opening after downloading
我正在使用 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)
我可以下载所需的文件,但其中大部分都已损坏。
我应该做哪些更改才能使代码正常工作。
目前无法测试 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
的使用,在 post ftp.retrbinary() help python by steveha.
下反应很好
关于使用上下文管理器打开和写入文件,请参阅How to open a file using the open with statement, and handling exceptions (Python 3 documentation), as quoted by sir-snoopalot
另请查看 ftplib
模块文档以获得进一步说明。
希望对您有所帮助。
我没有试过你的代码,但在查看 Python 文档时你可能忘记了关闭文件并正确退出,所以文件缓冲区可能没有完全写入磁盘。
试试这个:
with open(download_path+ doc,'wb') as fp:
ftp.retrbinary(f"RETR {doc}", file.write)
ftp.quit()
with语句会在退出该块时执行文件的close函数
您忘记关闭文件。只需在代码末尾添加以下内容即可。
file.close()
我正在使用 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)
我可以下载所需的文件,但其中大部分都已损坏。 我应该做哪些更改才能使代码正常工作。
目前无法测试 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
的使用,在 post ftp.retrbinary() help python by steveha.
关于使用上下文管理器打开和写入文件,请参阅How to open a file using the open with statement, and handling exceptions (Python 3 documentation), as quoted by sir-snoopalot
另请查看 ftplib
模块文档以获得进一步说明。
希望对您有所帮助。
我没有试过你的代码,但在查看 Python 文档时你可能忘记了关闭文件并正确退出,所以文件缓冲区可能没有完全写入磁盘。
试试这个:
with open(download_path+ doc,'wb') as fp:
ftp.retrbinary(f"RETR {doc}", file.write)
ftp.quit()
with语句会在退出该块时执行文件的close函数
您忘记关闭文件。只需在代码末尾添加以下内容即可。
file.close()