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

本小妞迷上赌 提交于 2019-12-25 04:57:29

问题


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

回答1:


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




回答2:


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



回答3:


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))


来源:https://stackoverflow.com/questions/41446353/how-do-i-work-out-the-difference-in-numbers-when-reading-and-writing-to-text-fil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!