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 t
Solution 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.
defmenu():
target = 85withopen('homework.txt','r') as a_file:
for l in a_file:
name, number = l.split(',')
number = int(number)
print(name + ': ' + ('passed'if number>=target elsestr(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
Solution 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.
withopen('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
Solution 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))
Post a Comment for "How Do I Work Out The Difference In Numbers When Reading And Writing To Text Files In Python?"