Search code examples
pythonfunctionfilenew-operator

how to parse this kind of file using python?


I'am new to programming and Python and I' struggling with my task. The task:

''The lines of the file store the names of the students and the average of their grades, separated by spaces (e.g."John 9.5"). The program rounds student averages and divides students accordingly into groups (students with an average of 10, 9, 8, 7, etc.) and write to different files.Use functional programming''

The file looks like that:

John 9.5
Anna 7.8
Luke 8.1

I don't understand how to take just numbers and round them and then how to make name and number like one element and put them in different files by their grades.

I tried:

f = open('file.txt')
sar = []
sar = f.read().split()
print(sar)
d = sar[::2]
p = sar[1::2]
print(p)

p = [round(float(el)) for el in p]
print(p)

f.close()

and this:

f = open('duomenys.txt')
lines = [line.rstrip('\n') for line in f]
print(lines)

        
f.close()

Solution

  • So by your question I understand that you just need to sort the data in a file based upon the students averages and place them in different files. To achieve I think you can use this.

    def sorting():
        infile = open("file.txt", 'r')
        data = infile.read().splitlines()
        for item in data:
            item = item.split(' ')
            item[1] = round(float(item[1]))
            print(item)
            placing(item[0], item[1])
    
    
    def placing(name, grade): #to place the students in sorted files
        if grade == 10:
            infile = open('10.txt', 'a')
            infile.write(f"{name} {grade}")
        elif grade == 9:
            infile = open('9.txt', 'a')
            infile.write(f"{name} {grade} \n") #further you can create more files.
    
    
    sorting()