简体   繁体   中英

How do I work out the difference in numbers when reading and writing to text files in python?

Alright, so I am studying python as a hobby, and I need to write a program that: should look at data for each student and calculate the number of marks a student needs to achieve the minimum score when they re-sit their exam. So I am going to say that the minimum score that a user needs to pass their exam is 85, and if a student record says 80, they would need 5. I have written the text file, and started the python code, but I have hit a dead end, any help would be greatly appreciated. Many thanks in advance!

Python:

def menu():
with open('homework.txt','r') as a_file:
    contents_of_file = a_file.read()
print(contents_of_file)
input()

Text file:

emma smith,79
noah jones,32
olivia williams,26
liam taylor,91
sophia green,80
mason brown,98

Instead of reading the whole file at once, we will look at each line individually. We'll use split to divide the lines into a name and a number, then use int to convert the string of a number into a numeric type.

def menu(): 
    target = 85   
    with open('homework.txt','r') as a_file:
        for l in a_file:
            name, number = l.split(',')
            number = int(number)
            print(name + ': '  + ('passed' if number>=target else str(target - number)))
    input()

('passed' if number>=target else str(target - number)) is just a way of doing an if statement in one line for simple things

There is other possibilities and shorter ways, but to give you a basic understanding, this might help: This should read each line and split it at the comma.

with open('homework.txt','r') as a_file:
    for line in a_file.readlines():
        split_line=line.split(",")
        name=split_line[0]
        score=split_line[1]
        YOUR CODE HERE

The pandas package is great for manipulating text files like yours. While it might be overkill for your current scenario, it may be useful to learn.

import pandas as pd

marks_needed = 85
df = pd.read_csv('homework.txt', header=None)

for name, marks in df.values:
    if marks > marks_needed:
        print('{} passed!'.format(name)
    else:
        extra_marks = marks_needed - marks
        print('{} needs {} more marks'.format(name, extra_marks))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM