首页 > 解决方案 > EOFError - 使用 ftplib 上传 .csv 文件

问题描述

我试图在 python3 上使用 ftplib 上传 .csv 文件。我的代码如下所示:

from ftplib import FTP_TLS
import os, sys

def get_script_path():
    return os.path.dirname(os.path.realpath(sys.argv[0]))

script_path = get_script_path()
ftp = FTP_TLS(host='hostedftp.com')
ftp.login('USER','123456789')
ftp.prot_p() 

filename = script_path + '/Test.csv'
fp = open(filename, 'r')
ftp.storlines("STOR " + filename, fp)

ftp.close()

我得到:

文件“ftp_test.py”,第 15 行,在 ftp.storlines(“STOR” + 文件名,fp) ... 文件“/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ftplib.py ",第 208 行,在 getline 中引发 EOFError EOFError

知道为什么吗?

标签: pythonpython-3.xcsvftplib

解决方案


我建议您切换到使用二进制模式。这还涉及使用rb. 例如:

from ftplib import FTP_TLS
import os, sys

def get_script_path():
    return os.path.dirname(os.path.realpath(sys.argv[0]))

script_path = get_script_path()
ftp = FTP_TLS(host='hostedftp.com')
ftp.login('USER','123456789')
ftp.prot_p() 

filename = 'Test.csv'

with open(os.path.join(get_script_path(), filename), 'rb') as fp:
    try:
        ftp.storbinary("STOR " + filename, fp)
        ftp.quit()   # This can raise EOFError if the connection has closed 
    except EOFError:
        pass

ftp.close() 

如果文件上传正常,您还可以捕获EOFError连接关闭时可能引发的问题。


推荐阅读