【问题标题】:How do I use ftp.storbinary to upload a file? [duplicate]如何使用 ftp.storbinary 上传文件? [复制]
【发布时间】:2020-12-13 02:06:50
【问题描述】:

我刚刚开始学习 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

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

【问题讨论】:

  • 这是一条响应消息,表示它是由 ftp 服务器生成的。目标机器上是否存在/public_html,ftp服务器进程是否有写入权限?
  • 我想展示的是,我可以使用 curl 将相同的文件上传到主机上的相同目录。我的代码中一定有错字或其他错误,但我找不到它
  • 好吧,我瞎了。您在 STOR 上使用完全限定名称。那应该是远程名称。 ftp.storbinary('STOR requested.txt', open(myfile, 'rb'))(或使用os.path.split(myfile)[1]
  • 谢谢。使用远程名称有效。感谢您的帮助。

标签: python ftp ftplib


【解决方案1】:

读取回溯,错误在处理来自服务器的响应的 ftp 堆栈深处。 FTP 服务器消息不是标准化的,但从文本中可以清楚地看出 FTP 服务器无法在远程端写入文件。这可能由于多种原因而发生 - 可能存在权限问题(FTP 服务器进程的身份对目标没有权限),写入在服务器上的沙箱设置之外,或者甚至它已经打开在另一个程序中。

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

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

【讨论】:

    【解决方案2】:

    “该文件”是指您尝试上传到 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()
    

    【讨论】:

    • 如果是这样,那将是IOErroropen 并列。相反,我们看到错误位于getresp 中的 ftp 堆栈的下方——这是来自 ftp 服务器的响应。
    猜你喜欢
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-10
    • 2021-07-07
    • 2013-10-31
    • 2015-02-08
    • 1970-01-01
    相关资源
    最近更新 更多