Question

I have edited the following script snippet to acumplish a ranking function for my dataset. Now when I get this to run as part of a looping script it appends the data to the end column of the csv over and over. In other words the csv just accumilates columns.

I am not sure how to do this, but I need the code to always enter the data into column 17. Currently on first run of the script the csv contains 16 columns however on second run the csv contains 25 columns, and there is need to overwrite column 17 on second run, not just append the results into row 26.

The code used:

import csv
from itertools import count
from collections import defaultdict
from functools import partial

counts = defaultdict(partial(count, 1))  # create a new count starting at 1

# Read in the data
with open('../MODIFIED.csv', 'rb') as f:
    # if you have a header on the file
    # header = f.readline().strip().split(',')
    data = [line.strip().split(',') for line in f]
    
with open("../MODIFIED.csv", 'wb') as outfile:
    writer = csv.writer(outfile)
    for counter, row in enumerate(data):
        counter += 1
        if counter >=2:
            row[9] = next(counts[row[2]])  # get the next count value
        writer.writerow(row)

Any ideas, help or suggestions will be greatly appreciated. I can provide more detail and an example if required, I am currently trying to keep things concise. Thanks in advance SMNALLY

Was it helpful?

Solution

wrong code submitted for sure..

OTHER TIPS

I'm not able comment in your problem that's why i post in Answer, Please add more information and some example. and why you are using open function use the csv.Dictreader() its gives the each column as dict, its easy to process also...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top