简体   繁体   中英

How do I create a text file that contain a list of results in python

I am studying JavaScript and Python at the moment, and I am reading and writing to text files in Python at the moment. Currently, I am trying to: write a program that should, when instructed to do so, create a file, that contains a list of students that need to re-sit and the number of marks they need to score to get a minimum of 85.

I have already written code that displays whether or not a student has hit the minimum score of 85, and if they haven't, how many more marks they need. But now I'm stuck. Any help would be very greatly appreciated, thanks!

Python:

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

Text File:

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

You just need to open a file to write the prints:

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

It sounds like you just want to pipe the results of your program into another textfile.

python file.py > results.txt should do the trick.

(I didn't check your algorithm, as you mention that it's doing what you want it to do already)

It seems to me that you are trying to achieve the following:

  1. Get the data from a text file, which you kind of did it
  2. Get a user input to open a new text file: reSit = input("Enter file name for the re-sit: ")
  3. Create a file to write to it fh = open(reSit ,'w')
  4. write to a file fh.write(<a fails student> + '\\n')
  5. Close the file

if you want to append to a file replace 3 by fh = open(reSit ,'a')

I guess this might do what you need ...

def menu():
    out_file = open("results.txt", "w")
    target = 85   
    with open("homework.txt", "r") as a_file:
        for l in a_file:
            name, number = l.split(",")
            number = int(number)
            out_file.write("{},{}\n".format(name, ('passed' if number>=target else str(target - number))))
menu()

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