【问题标题】:Unable to send the file through FTP using python 2.6无法使用 python 2.6 通过 FTP 发送文件
【发布时间】:2016-01-03 10:16:32
【问题描述】:

我已经尝试了下面的代码并改变了所有可能的方式,比如

storbinarystorlinesrrbrb+ 但即使将文件传输到服务器没有运气。这是我的示例代码:

    from ftplib import FTP
    ftpfile = FTP('hostname')
    print "Connected with server"
    ftpfile.cwd('path of server where file need to store')
    print "Reached to target directory"
    myFile = open(inputfile, 'rb+')
    ftpfile.storbinary('STOR ' +inputfile, myFile)
    print "transferring file..."
    myFile.close()
    print "file closed"
    ftpfile.quit()
    print "File transferred"

代码只是运行并输出所有打印语句,但是当我检查服务器时没有创建文件。考虑登录成功。

需要建议以实现所需的输出。谢谢

【问题讨论】:

  • 你应该查看storebinary的回复
  • inputfile 到底是什么?
  • @BurhanKhalid 输入文件是我本地系统中的文本文件。例如 inputfile='c:\working\cyborg.txt'
  • 如果你不检查任何命令的结果,你怎么可能知道发生了什么。它在机翼和祈祷上编码。
  • @RolfofSaxony 这是一个很好的例子,无论如何问题都解决了,谢谢大家

标签: python ftp ftp-client


【解决方案1】:

你没有登录,所以你不能做任何事情。你确定inputfile 设置了吗?

from ftplib import FTP
ftp = FTP('hn')
ftp.login('username', 'password')
ftp.cwd('working_dir')
myfile = open(myfile.txt, 'rb')
ftp.storbinary('STOR ' + myfile, myfile)
ftp.quit()
# No need to close() after quit.

或者,您可以使用以下方法在打开连接时登录:

ftp = FTP('hn', 'username', 'password')

那就更好了:

from ftplib import FTP
ftp = FTP('hn', 'username', 'pass')
ftp.cwd('working_dir')
with open(myfile, 'rb') as f:
    ftp.storbinary('STOR ' + myfile, f)

ftp.quit()

【讨论】:

  • 记录已成功完成,我已经更新了我的问题
  • 请将您的代码与问题中给出的代码进行比较,基本上两者是相同的,它还没有工作。
  • 没错,但尝试排除这一点可能是有价值的。你检查文件权限了吗?
  • 我试过伙计,任何方式都解决了问题,非常感谢你。 :)
【解决方案2】:

你需要传递STOR the filename on the remote server,因为你正在传递一个路径。

您还需要使用storlines,因为您发送的文件只是一个纯文本文件。

试试这个:

import os
from ftplib import FTP

local_file = r'C:\working\cyborg.txt'
remote_file_name = os.path.basename(local_file)

ftp = FTP('host', 'username', 'password')
ftp.cwd('/some/path/on/server')
ftp.storlines('STOR %s' % (remote_file_name,),
              open(local_file, 'r'))
ftp.quit()

【讨论】:

  • 请在字符串格式中加0。例如 ftp.storlines('STOR {0}'.format(remote_file_name)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 2013-12-16
  • 1970-01-01
  • 1970-01-01
  • 2020-03-23
相关资源
最近更新 更多