如何使用ftp.storbinary上载文件?

2024-09-29 17:45:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习Python。我正试图上传一个文件,如下所示:

import ftplib
myurl = 'ftp.example.com'
user = 'user'
password = 'password'
myfile = '/Users/mnewman/Desktop/requested.txt'
ftp = ftplib.FTP(myurl, user, password)
ftp.encoding = "utf-8"
ftp.cwd('/public_html/')
ftp.storbinary('STOR '+myfile, open(myfile, 'rb'))

但会出现以下错误:

Traceback (most recent call last):
  File "/Users/mnewman/.spyder-py3/temp.py", line 39, in <module>
    ftp.storbinary('STOR '+myfile, open(myfile, 'rb'))
  File "ftplib.pyc", line 487, in storbinary
  File "ftplib.pyc", line 382, in transfercmd
  File "ftplib.pyc", line 348, in ntransfercmd
  File "ftplib.pyc", line 275, in sendcmd
  File "ftplib.pyc", line 248, in getresp
error_perm: 553 Can't open that file: No such file or directory

“那个文件”指的是什么?我需要做什么来修复这个问题


Tags: 文件inlineftppasswordopenmyfileusers
2条回答

读取回溯时,错误深入到ftp堆栈中,处理来自服务器的响应。FTP服务器消息没有标准化,但从文本中可以清楚地看出,FTP服务器无法在远程写入文件。发生这种情况的原因多种多样——可能是权限问题(FTP服务器进程的标识没有对目标的权限)、写入不在服务器上的沙盒设置范围内,甚至写入已在另一个程序中打开

但在您的情况下,当“STOR”命令需要目标路径时,您正在使用完整的源文件名。根据是否要在服务器上写入子目录,计算目标名称可能会变得复杂。如果只需要服务器的当前工作目录,可以

ftp.storbinary(f'STOR {os.path.split(myfile)[1]}', open(myfile, 'rb'))

“该文件”指的是您试图上载到FTP的文件。根据您的代码,它引用以下行:myfile = '/Users/mnewman/Desktop/requested.txt'。出现此错误是因为Python在路径中找不到文件。检查它是否存在于正确的路径中。如果要测试脚本中是否存在错误,可以将测试文件添加到Python脚本所在的目录中,然后使用该文件的路径运行脚本

FTP上载的示例脚本:

import ftplib
session = ftplib.FTP('ftp.example.com','user','password')
file = open('hello.txt','rb')                  # file to send
session.storbinary('STOR hello.txt', file)     # send the file
file.close()                                    # close file and FTP
session.quit()

相关问题 更多 >

    热门问题