Search code examples
pythonfiletext-filesreadfilenotepad

Python: Reading marks from a file then using marks to get class


I have gotten this sheet and I am having trouble with it. The Task

This is my notepad txt: maths_mark I want to create it like if:

  • mark => 90 = 10M1
  • mark => 80 = 10M2
  • mark => 70 = 10M3
  • mark => 60 = 10M4
  • mark => 50 = 10M5
  • mark => 40 = 10M6
  • mark => 30 = 10M7
  • mark => 20 = 10M8
  • mark => 10 = 10M9

I am stuck on how to read the marks from the file then creating a new text file with the names, marks and class.

If anyone can be any help, it would be appreciated.

Thanks, Noob Coder


Solution

  • import csv
    
    # function to process data
    def process_data(data):
        for item in data:
            marks = int(item[2])
            mclass = 'incorrect data entry try again'
            if marks == 0:
                mclass = "10.9"
            elif marks >= 0 and marks <= 100:
                mclass = "10.{}".format(10 - int(item[2][0]))
            yield '"{}","{}",{},{}'.format(item[0],item[1],item[2],mclass)
    
    # read data to memory
    data = []
    with open("Maths_Mark.txt", "r") as csv_in:
        data = list(csv.reader(csv_in, delimiter=','))
    
    # write contents to file
    with open('Maths_Group.txt', 'w') as csv_out:
        for line in process_data(data):
            csv_out.write(line + "\n")