在python中读取和写入文本文件时,如何计算数字的差异? [英] How do I work out the difference in numbers when reading and writing to text files in python?

查看:26
本文介绍了在python中读取和写入文本文件时,如何计算数字的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我正在将 Python 作为一种爱好来学习,我需要编写一个程序:应该查看每个学生的数据并计算学生在重考时达到最低分数所需的分数考试.所以我要说的是,用户需要通过考试的最低分数是 85,如果学生记录显示 80,他们需要 5.我已经编写了文本文件,并启动了 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!

蟒蛇:

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

文本文件:

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

推荐答案

我们不会一次读取整个文件,而是单独查看每一行.我们将使用 split 将行分成名称和数字,然后使用 int 将数字字符串转换为数字类型.

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)) 只是为了简单的事情在一行中做一个 if 语句

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

这篇关于在python中读取和写入文本文件时,如何计算数字的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆