FTP传输损坏的ZIP文件

-1 投票
1 回答
733 浏览
提问于 2025-04-17 04:49

我用这段代码从FTP服务器下载一个zip文件,但下载下来的文件是坏的。有人知道为什么吗?

from ftplib import FTP
import getpass

user = raw_input('Username: ')
password = getpass.getpass()
host = raw_input('Host:')
ftp = FTP(host,user,password)
ftp.retrlines('LIST')
f_file = raw_input('What is the name of the file you would like to download? ')
print 'Opening local file...'
l_file = open(f_file, 'w')
print "Getting", f_file
ftp.retrbinary('RETR ' + f_file, l_file.write)
print "Closing", f_file
l_file.close()
print 'Closing FTP connection'
ftp.close()

1 个回答

3

这可能是因为你在以ASCII模式写本地文件,而不是以二进制模式,这样会把所有的0A字节变成0D0A(换行符变成了回车加换行),导致二进制文件损坏。

再试一次,使用l_file = open(f_file, 'wb')来打开文件。

撰写回答