用FTP上传后,我的文本文件中没有任何内容

2024-10-01 19:34:39 发布

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

目前,用户输入保存为一个文件在电脑上,我想它也要上传到我的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")

Tags: thetexttxtformatforisareafile
1条回答
网友
1楼 · 发布于 2024-10-01 19:34:39

你为什么要注释掉这行text_file.close()?对于这样的代码,不能保证在您要发送文件的时候会将任何内容写入该文件。我认为最好的方法是先关闭文件(再次在close()行中添加注释),或者如果不想重新打开同一个文件来调用text\u 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?

相关问题 更多 >

    热门问题