如何写入txt文件的多个参数(字符串和变量)

时间:2017-06-26 17:37:57

标签: python file-writing

我正在尝试创建一个程序,它接受单词短语的开始时间和结束时间,减去它们以查找时间长度,并将每个短语的长度写入文件。我想最终的结果是"短语#(NumTrials)的长度是:(长度)"长度和numtrials是变量。我尝试了几种不同的方法,但是python告诉我它只需要1个参数用于write函数。我怎么能修改这个,以便每个短语每次都记录在新行上?

from decimal import Decimal, getcontext
getcontext().prec = 4
def main():
    myfile = open('Phrases Compiled.txt', 'w')
    NumTrials = 0
    SumLength = 0
    StoreLengths = dict()
    response = input("are there more calculations you'd like to do?")
    while response != "no":
        if response in ['yes', 'y', 'Yes', 'Y']:
        start, stop = eval(input("what is the start and stop times of the phrase?"))
        start = Decimal(start)
        stop = Decimal(stop)
        length = stop - start
        StoreLengths[NumTrials] = length
        NumTrials += 1
        SumLength += length
        print(length)
        length = str(length)
        NumTrials = str(NumTrials)
        myfile.write("the length of phrase #", NumTrials, "is: ",length"\n")
        response = input("are there more calculations you'd like to do?")
    elif response in ['no', 'n', 'N', 'No']:
        print("calculations are done")
        break 
averagelength = SumLength/NumTrials
print("average length was:", averagelength)

main()的

3 个答案:

答案 0 :(得分:1)

你连串错了......

myfile.write("the length of phrase #", NumTrials, "is: ",length"\n")

应该是

myfile.write("the length of phrase #" + str(NumTrials) + "is: " + str(length) + "\n")
# But even with "+" I guess it would be wrong to add strings and decimal objects together... Hence the "str(...)" but it is kinda bad.

所以最好的选择:

myfile.write("the length of phrase #%d is: %f\n" % (NumTrials, length))

编辑:我猜你在if response in ['yes', ...]之后也错误地编写了代码,因为Python不允许格式化。

答案 1 :(得分:0)

我认为您忘记了正确连接字符串。 这应该可以解决问题:

Origin

编辑:问题已经回答

答案 2 :(得分:0)

在格式化字符串时我个人喜欢使用string.format()

myfile.write("the length of phrase #", NumTrials, "is: ",length"\n")

会变成

myfile.write("the length of phrase {} is: {}\n".format(NumTrials, length))