【问题标题】:Multiple Input and sending results to text多输入并将结果发送到文本
【发布时间】:2017-10-26 12:43:06
【问题描述】:

请不要只给出答案。我是新手,这是我的学习方式。如果您能多花点时间解释一下原因或方式,我将不胜感激。

我需要获取我希望用户输入的多个输入:ID、金额、小费金额。金额和小费的多个实例。然后移植到文本文件 类似这样的格式:日期、员工编号、金额、总金额、小费金额、小费总和。

## Program gets the date, Employee ID, and amounts.  
## It then places them into a text file which can be ported to excel.

## Get Date


## Get Employee I.D.
empnum = raw_input('Please enter Employee Number\n')

## Gets the amounts.
num1 = raw_input('Please enter Ticket amount.\n')
num2 = raw_input('Please enter tip amount.\n')

## Sum of the amounts.
sum = float(num1) + float(num2)

## Information to be ported to text file.
## Date, Employee ID, amount, Total sum of amount, tip amount, total sum of tip
print'Employee ' + empnum + ' total is' 
print(sum)

【问题讨论】:

    标签: python input io


    【解决方案1】:

    您必须读取所需数据类型的输入。

    empnum = raw_input('Please enter Employee Number\n')
    num1 = float(raw_input('Please enter Ticket amount.\n'))
    num2 = float(raw_input('Please enter tip amount.\n'))
    

    现在你需要做的是你必须在写模式下使用open函数打开一个文件处理程序。

    fle =open("C:\Python27\projects\infile.txt",'w')
    

    做你的计算

    sum = num1 + num2
    

    您需要使用write 函数将其写入文件,而不是打印

    fle.write('Employee ' + empnum + ' total is ' + str(sum))
    

    然后关闭文件

    fle.close()
    

    【讨论】:

    • 谢谢。我理解得更好,可以实施您的解决方案。每次运行时都会覆盖该文件吗?如果是这样,将 open("test.txt", "a") as infile: infile.write("appended text") 修复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 2018-07-31
    • 2021-02-25
    • 2021-07-03
    • 2015-09-23
    • 1970-01-01
    相关资源
    最近更新 更多