【问题标题】:Python ftp upload bug: no attribute 'rfind'Python ftp 上传错误:没有属性 'rfind'
【发布时间】:2016-04-26 13:18:20
【问题描述】:

我正在用 getopt 编写一个 ftp 上传器。如果使用fullname = 'file.jpg' 一切正常,但如果fullname = newfiles 没有打开并返回错误通知:

AttributeError: 'list' 对象没有属性 'rfind'

也许我的应用没有发送文件的权限?

#!/usr/bin/env python
# -*- coding: utf-8 -*-  

import sys
import getopt
import ftplib
import os

def usage():
    print "Home"
#if __name__ == "__main__":
try:
    opts, args = getopt.getopt(sys.argv[1:], "uhc", ["upload=", "help", "connect"])
except getopt.GetoptError:
    usage()
    sys.exit(2)


if opts == []:
    usage()

for opt, arg in opts:
    if opt in ("-h", "--help"):
        usage()
    elif opt in ("-u", "--upload"):
        newfile = args
        if not file:
            print "Nie wybrano pliku!"
        else:
            print "Wybrany plik",newfile
            ftp = ftplib.FTP()
            ftp.connect('host')
            ftp.login('user', 'pass')
            ftp.cwd('./')
            print "Wybieram:", ftp.pwd()
            print "Wgrywam"
            fullname = newfile
            name = os.path.split(fullname)[1]
            f = open(fullname, "rb")
            ftp.storbinary('STOR ' + name, f)
            f.close()
            print "OK"

            print "Files:"
            print ftp.retrlines('LIST') 
            ftp.quit()
    elif opt in ("-c", "--connect"):
        print "a"

【问题讨论】:

    标签: python bash file-upload ftp getopt


    【解决方案1】:

    我认为您的脚本可以进行一些修改。错误是由于将列表传递给 os.path.split() 函数。

    我建议如下:

    根据getopt 文档,需要参数的选项后应跟一个冒号“:”。

    改变这一行:

    opts, args = getopt.getopt(sys.argv[1:], "uhc", ["upload=", "help", "connect"])
    

    为此(在选项列表中的 u 之后添加一个冒号):

    opts, args = getopt.getopt(sys.argv[1:], "u:hc", ["upload=", "help", "connect"])
    

    然后在你的 for 循环中,arg 变量将被填充 filname。设置 newfile = arg 而不是 args。

    改变这个:

        elif opt in ("-u", "--upload"):
            newfile = args
    

    对此(arg而不是args):

        elif opt in ("-u", "--upload"):
            newfile = arg
    

    更改后,您应该能够运行包含 1 个或多个文件的脚本,例如: your_script.py -u "file1.jpg" -u "file2.jpg"

    另外,如下代码:

    if not file:
            print "Nie wybrano pliku!"
        else:
            print "Wybrany plik",newfile
    

    在这种情况下,“文件”是 python 内置的,应该始终属于 else 条件。另一种选择可能是使用os.path.isfile(newfile) 检查文件是否存在。

    【讨论】:

    • if change uhc to u:hc not turn to my if if not file: print "Nie wybrano pliku!" else: print "Wybrany plik",file if empty view usage(), 为什么?
    • 请举例说明如何调用脚本。我编辑了我的答案以尝试提供帮助。您的“if note file:”语句是否仍然与您问题中的当前代码匹配,还是完全改变了?
    猜你喜欢
    • 2016-07-01
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 2014-07-08
    相关资源
    最近更新 更多