【问题标题】:Nothing In My Text File After Uploaded With FTP使用 FTP 上传后,我的文本文件中没有任何内容
【发布时间】:2014-01-21 19:07:12
【问题描述】:

目前用户的输入被保存为计算机上的文件,我想也希望将它上传到我的 ftp 服务器,我已经让它工作了,但文件中没有任何内容,很可能因为我是编程新手,所以很容易出错,谢谢

quotation = input("Do you want to save a quotation? ")

if (quotation == "yes") :
    quotationName = input("What do you want to save the quotation as? ")

    text_file = open("{}.txt".format(quotationName),"w") #(w) opens files in write
    text_file.write ("The total lawn area is {}\n".format(totalAreaLawn))
    text_file.write ("The total for the lawn is £{}\n\n".format(totalCostLawn))
    text_file.write ("The total concrete area is {}\n".format(totalAreaConcrete))
    text_file.write ("The total for the concrete is £{}\n\n".format(totalCostConcrete))
    text_file.write ("The total wooden deck area is {}\n".format(totalAreaWoodenDeck))
    text_file.write ("The total for the wooden deck is £{}\n\n".format(totalCostWoodenDeck))
    text_file.write ("The total rectangular pond area is {}\n".format(totalAreaRectangularPond))
    text_file.write ("The total for the wooden deck is £{}\n\n".format(totalCostRectangularPond))
    text_file.write ("The total number of water features needed is {}\n".format(numberOfWaterFeatures))
    text_file.write ("The total for the water features is £{}\n\n".format(totalCostWaterFeatures))
    text_file.write ("The total number of garden lights needed is {}\n".format(numberOfGardenLights))
    text_file.write ("The total for the garden lights is £{}\n\n".format(totalCostGardenLighting))   

    #text_file.close()

    ftpconnect = ftplib.FTP('landscapegardening.freeiz.com','a6011438','L0g1tecH')

    saveDirectory = '/public_html/Quote'

    ftpconnect.cwd(saveDirectory)

    fileSend = open("{}.txt".format(quotationName),'rb')
    ftpconnect.storbinary('STOR {}.txt'.format(quotationName), fileSend)

    fileSend.close()
    ftpconnect.quit()      

    print("Quotation saved")

【问题讨论】:

    标签: python ftp


    【解决方案1】:

    你为什么注释掉text_file.close()这一行?使用这样的代码,无法保证在您要发送文件的位置将任何内容写入文件。我认为最好的方法是先关闭文件(只需再次在 close() 行中注释),或者如果您不想重新打开同一个文件来调用 text_file.flush() 然后调用os.fsync(text_file)。如果您选择第二个选项,请记住将 ftpconnect.storbinary('STOR {}.txt'.format(quotationName), fileSend) 更改为 ftpconnect.storbinary('STOR {}.txt'.format(quotationName), text_file)。您还必须将打开模式更改为 'r+' 并使用 text_file.seek(0) 转到文件的开头。

    编辑:刚刚看到您实际上只需要一个类似文件的对象,有关详细信息,请参见此处: Can I upload an object in memory to FTP using Python?

    【讨论】:

    • 在我尝试测试使其工作的方法时将其注释掉,只是取消注释它并且效果很好,谢谢! :)
    猜你喜欢
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-02
    • 2012-10-24
    • 2017-07-13
    • 2015-07-21
    相关资源
    最近更新 更多