使用保存到文件的值来计算平均值/中值/模式/等

时间:2014-03-13 03:50:01

标签: python file-io

我有一个程序可以保存一个可以写入值的文件。我想要做的是使用保存的文件来计算我的平均值/中位数/模式,并能够删除值。功能。我可以通过打开("文件名"," a")来为文件添加值...但是如何创建它以便我能够导入文件值计算我的其他功能?

很抱歉这么久,但是如果有人可以提供帮助我真的很感激,我很想知道File IO的一些东西。

filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")

def main(filename):

    print("Now what would you like to do?")
    print("--------------------------------------------------------------------------------")
    print("Press 1 if you would like to ADD a Value to your list")
    print("Press 2 if you would like to DELETE a Value from your list according to its value")
    print("Press 3 if you would like to DELETE a Value from your list according to its location")
    print("Press 4 if you would like to DISPLAY your List")
    print("Press 5 if you would like to COMPUTE MEAN for your list")
    print("Press 6 if you would like to COMPUTE MEDIAN for you list")
    print("Press 7 if you would like to COMPUTE MIDPOINT for you list")
    print("Press 8 if you would like to COMPUTE MODE(S) for your list")
    print("Press 9 if you would like to COMPUTE STANDARD DEVIATION for your list")
    print("Press 10 if you would like to READ values from a FILE you have made")       
    print("Press 0 if you would like to EXIT")
    print()


    execute = int(input("which action would you like to do next?"))
    if execute == 1:
        add_Values(filename)
    if execute == 2:
        remove_Value_List(filename)
    if execute == 3:
        del_Value_Location(filename)
    if execute == 4:
        read_file(filename)
    if execute == 5:
        computing_Mean(filename)
    if execute == 6:
        computing_Median(filename)
    if execute == 7:
        computing_Midpoint(filename)
    if execute == 8:
        computing_Modes(filename)
    if execute == 9:
        computing_Standard_Dev(filename)
    if execute == 10:
        read_file(filename)
    if execute == 0:
        print()
        print("That's too bad I was having so much fun...but okay...bye!")
    if execute >= 12:
        print("Sorry but that is not one of the options")
    if execute <= -1:
        print("Sorry but that is not one of the options")

def add_Values(filename):
    fout = open(filename,"a")

    again = 'y'
    while again == 'y':
        fout.write(input("Enter a number you want to write to the file:")+"\n")
        print("Do you want to add another number?")
        again = input("y = yes, anything else = no:")
    fout.close()
    print("The numbers have been saved to the file")

    main(filename)

def remove_Value_List(filename):
    fout = open(filename, "r")
    fout.readlines()
    remove = "y"

    while remove == "y":
        print()
        print("Here is your list:")
        add_Values(filename)
        number_list = float(input("Which value should I remove?"))

        try:
            values.remove(number_list)
            print("Here is the revised list:")       
            print()
            print()
        except ValueError:
            print("That item is not found in the list.")
            number_list = float(input("which value should I remove?"))
        remove = input("Would you like to remove a value? y = yes, amything else = no:")
    fout.close()
    print()

    main(filename)
def del_Value_Location(filename):

    remove = "y"
    fout = open(filename,"r")
    fout.readlines()

    while remove == "y":
        print()
        print("Here is your list:")
        add_Values(filename)
        number_list = int(input("Which position should I remove?"))

        try:
            del values[number_list]
            print("Here is the revised list:")       
            read_file_one(filename)
            print()
        except ValueError:
            print("That item is not found in the list.")
            number_list = float(input("which value should I remove?"))
        remove = input("Would you like to remove a value? y = yes, amything else = no:")
    fout.close()
    print()

    main(filename)

def computing_Mean(filename):

    with open(filename,"r") as fout:
        summ = 0
        cnt = 0
        for line in fout.readlines():
            cnt += 1
            summ += float(line.strip())
        print ("Mean value is:" (summ/cnt))

def computing_Median(filename):           

    fin = open(filename,"r")
    fin.readlines()
    ordered = sorted(filename)
    length = len(filename)
    print("The median of this list is:")
    print(float((ordered[length//2] + ordered[-(length+1)//2]))/2)

    main(filename)

def computing_Midpoint(filename):
    with open(filename,"r") as fout:
        filename.sort(key=int)
        minNum = min(float(filename))
        maxNum = max(float(filename))
        print("The midpoint of this list is:")
        print((minNum + maxNum) / 2)

    main(filename)

def computing_Modes(filename):

    from collections import Counter
    data = Counter(filename)
    print("The Mode(s) of this list is/are:")  
    print(data.most_common(1))

    main(filename)

def computing_Standard_Dev(filename):

    mean = sum(filename)/len(filename)
    for i in values:
        total = 0
        newDev = i - mean
        squared = newDev**2
        total = (total + squared)
        divider = (total/(len(values)-1))
        standardDev = divider**.5
    print("The standard deviation is:")
    print(standardDev)

    main(filename)


def read_file(filename):

    fin = open(filename, 'r')
    L = fin.readlines()

    for ix in range(len(L)):
        L[ix]=L[ix].strip()

    while "" in L:
        L.remove("")

    for ix in range(len(L)):
        L[ix]=float(L[ix])
    fin.close()

    print(L)
    main(filename)       

main(filename)

1 个答案:

答案 0 :(得分:0)

你的代码中有很多错误彼此非常相似,所以我只解释其中一个类似错误,你应该通过检查固定错误来解决其他问题。

首先,您要打开一个名为filename的文件。在它周围使用引号使它成为一个字符串。你应该像这样使用它:

def add_Values(filename):
    fout = open(filename,"w")

但使用with语句打开文件要好得多,因为即使引发异常,文件也会自动关闭。

def add_Values(filename):
    with open(filename) as fout:
    #do smth

def del_Value_Location(filename):和其他一些文件中没有可用的文件。您也应该在那些文件中打开文件。

要进行计算,您需要从文件中读取数据。这可以通过使用file.readlines()

来实现
def computing_Mean(filename):
    with open(filename,"r") as fout:
        summ = 0
        cnt = 0
        for line in fout.readlines():
            cnt += 1
            summ += int(line.strip())
        print ("Mean value is: %.1f" % (summ/cnt))

如果要更改要查看的位数,则应更改%.1f部分 有了这个,你应该自己修复其他的计算。

关于菜单,您可以执行以下操作,以便在不使用第二个功能的情况下再次显示。

filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
#exclude this filename in main and use it as `main`s argument.
def main(filename): 

    print("Now what would you like to do?")

此后,您应该将所有main_two()更改为main(filename)