user361403
user361403

Reputation: 53

Fill in missing data in CSV file in Python

I am new to python, I am trying to input some missing data into a csv file. I also want to divide the first values by 2.

This is the Input file:

5,1
6,1
10,1

Output file, fill in missing numbers from 0 and divide the first values by 2.

0/2, 0
1/2, 0
2/2, 0
3/2, 0
4/2, 0
5/2, 1
6/2, 1
7/2, 0
8/2, 0
9/2, 0
10/2, 1

This is my code so far, I started by opening the initial file then write the missing values into the new file starting from 0.

import csv

with open(r"C:\Users\Desktop\initial.csv") as f:  
    reader = csv.reader(f)
    
with open("C:\\Users\\Desktop\\newfile.csv", "w") as csvfile:  
   csvwriter = csv.writer(csvfile)  
   for i in range(11):     
        csvwriter.writerow([i,0])

I am stuck on how to check the initial file, compare to see if the new value is there, if it’s there, copy over to new file. Any help will be appreciated. I am also opened to an easier way of doing this. Thanks.

Upvotes: 0

Views: 865

Answers (1)

Olvin Roght
Olvin Roght

Reputation: 7812

You can iterate over csv file manually using next():

import csv

with open("initial.csv") as inp_f, open("newfile.csv", "w+") as out_f:
    reader = csv.reader(inp_f)
    writer = csv.writer(out_f)
    last_row = next(reader, None)
    for i in range(11):
        if last_row and last_row[0] == str(i):
            writer.writerow((i / 2, 1))
            last_row = next(reader, None)
        else:
            writer.writerow((i / 2, 0))

P.S. This will work only if rows in source file will be sorted by first column in ascending order.

Upvotes: 1

Related Questions