python - 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
知道为什么吗?
解决方案
我建议您切换到使用二进制模式。这还涉及使用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
连接关闭时可能引发的问题。
推荐阅读
- javascript - 如何在 React/Preact 应用程序中运行常规 JavaScript
- vba - Powerpoint Macro VBA - 选择“幻灯片图像”复选框
- php - 检查图像是否存在 - 数据库或文件查找?
- python - 如何根据用户在 Python 中的输入绘制 3D 正方形?
- python - 使用 and or not 开发表达式
- javascript - 如何将数据从input传到express,以便后面的express将数据传到数据库PostgreSQL
- javascript - 仅从每个对象 Javascript 中获取请求的项目
- excel - Excel 无法粘贴所有复制的单元格
- python - Python - 查找系列中连续 NaN 组的第一个和最后一个索引
- database - 如何在不在同一网络上的数据库和移动应用程序之间进行访问?