函数

时间:2017-11-13 19:14:57

标签: python

代码:

import os, csv

def menu():
    print("Welcome to da sporty ting" + "\n" + "Menu options: " + "\n")
    print("1 - Run the code")
    print("2 - Exit")
    menu_choice = int(input("Enter choice: "))
    while menu_choice not in (1, 2):
        menu_choice = int(input("Error, try again: "))

    if menu_choice == 1:
        finding_file()
    elif menu_choice == 2:
        exit()

def finding_file():
    print("\n")
    print("Text file options" + "\n")
    print("1 - testfile 1" + "\n" + "2 - testfile 2" + "\n" + "3 - Other")
    txt_menu_option = int(input("Enter choice: "))
    print("\n")
    while txt_menu_option not in (1, 2, 3):
        txt_menu_option = input(input("Error, try again: "))
    if txt_menu_option == 1:
        filename = "Test1_Votes.txt"
        pass
    elif txt_menu_option == 2:
        filename = "Test2_Votes.txt"
        pass
    elif txt_menu_option == 3:
        filename = str(input("Enter name of txt file (don't include .txt at he end) : "))
        filename = filename + ".txt"

        file_exists = os.path.exists(filename)

        if file_exists == False:
            print("File does not exist, returning to menu")
            menu()
        pass
    file_validity(filename)

def file_validity(filename):
    f = open(filename, 'r+')  # opening file in read/write mode
    inv_lines_cnt = 0
    valid_list = [0, 0, 1, 2, 3]  # sorted list of valid values
    lines = f.read().splitlines()
    f.seek(0)
    f.truncate(0)  # truncating the initial file

    for l in lines:
        if sorted(map(int, l.split(','))) == valid_list:
            f.write(l + '\n')
        else:
            print(l + " is a invalid line")
            inv_lines_cnt += 1
    print("There were {} invalid line/lines.".format(inv_lines_cnt))
    calculate_quota(filename)

def calculate_quota(filename):
    f = open(filename, 'r+')
    lines = f.readlines()
    print("Calculate quota " + str(lines))
    seats = 2
    line_count = 0
    for line in lines:
        line_count += 1
    quota = 0
    quota == int((line_count / (seats + 1)) + 1)
    print(quota)
    quota_required(quota, lines)

def quota_required(quota, lines):

    for line in lines:
        lines.rstrip(',')
        lines.rstrip('\n')
    print(lines)
    candidate_fp_votes = [0,0,0,0,0]
    for line in lines:
        for i in range(5):
            if line[i] == 1:
                print ("if working")
                candidate_fp_votes[i] += 1
                print (candidate_fp_votes)

    print (candidate_fp_votes)

文本文件示例:

1,2,3,0,0

0,0,3,2,1

1,0,0,3,2

1,0,0,2,3

0,1,2,3,0

目前我遇到一个问题,在file_validity()之后,文本文件似乎已经加载为空,就像我在下一个函数中重新打开文件时一样,它将行打印为空。 file_validity()只删除文件,并重写有效的投票。正如你所看到的,我试图找出问题所在。我认为截断和搜索功能似乎造成了一些麻烦,但我不确定这是否属实。如果是这样的话,如何解决它。

任何帮助?

提前致谢。

0 个答案:

没有答案