简体   繁体   中英

Python reading csv files and then writing them to another

I need to use if else statements to grade a csv file and then write them to another csv file.

with open('arvud.csv' , 'r') as arvud:
    for Hinne in arvud:
        print(Hinne)
        x= int(Hinne)
        if x > 90:
            print ("Hinne 5")
        elif 80 < x < 91:
            print ("Hinne 4")
        elif 70 < x < 81:
            print ("Hinne 3")
        elif 60 < x <71:
            print ("Hinne 2")
        elif 51 < x < 61:
            print ("Hinne 1")
        elif x < 50:
            print ("Hinne 0")

I have got the grading part but cant seem to find a way to write them to a csv file as two columns one for the the grade and for the score. [enter image description here][1]

You could change your print statements to append the grades to a list. Then write that list to a csv file. Like this:

data = []
with open('arvud.csv' , 'r') as arvud:
    for Hinne in arvud:
        print(Hinne)
        x= int(Hinne)
        if x > 90:
            data.append(5)
        elif 80 < x < 91:
            data.append(4)
        elif 70 < x < 81:
            data.append(3)
        elif 60 < x <71:
            data.append(2)
        elif 51 < x < 61:
            data.append(1)
        elif x < 50:
            data.append(0)

You should get a resulting list that looks something like [2, 4, 0...]

Then just write that list to a csv file like so:

import csv
with open('csv_file_name.csv', 'a+', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

You could also save time by appending each grade to the csv file each iteration but I wanted to provide an answer that used your code to help you understand what steps to take next based on what you've done so far.

You could redirect your current print statements to a file.

  • stdout is where print writes too (ie normally your terminal)
  • we can change this temporary to be a file

Code

 import sys

old_stdout = sys.stdout  # cache current setting of stdout

with open('arvud.csv' , 'r') as arvud, \
     open('out_arvud.csv', 'w') as sys.stdout:  # set stdout to file
    for Hinne in arvud:
        print(Hinne)
        x= int(Hinne)
        if x > 90:
            print ("Hinne 5")
        elif 80 < x < 91:
            print ("Hinne 4")
        elif 70 < x < 81:
            print ("Hinne 3")
        elif 60 < x <71:
            print ("Hinne 2")
        elif 51 < x < 61:
            print ("Hinne 1")
        elif x < 50:
            print ("Hinne 0")
            
sys.stdout = old_stdout # reset stdout initial setting

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