Home > Software design >  python program to read a csv and expand the range from a particular column
python program to read a csv and expand the range from a particular column

Time:12-21

I have a csv file which looks like this:

i need a new csv file which should have an extra column ranged which should be like this:

im new to python(coding) and i have this project in my col can someone help..

i need a desired out put which should not avoid zeros in the range and i need a python program

CodePudding user response:

Ok, so with the amount of information we have, lets get started

import csv

well, this was obvious


def getAllVars(varying):  ## The input is a list here [start, end] both start and end are string which we will parse
    start = int(varying[0])
    end = int(varying[1])
    n = len(varying[0])
    exp = "{0:0" str(n) "}"  ## this expression will be used to pad zeros if output length is not matching
    res = []
    for i in range(start,end 1):
        res  = [exp.format(i)]  ## just like I mentioned
    return res  ## so we return the expanded list

COL_TO_EXPAND=2

This constant to control which column to expand Rest should be pretty simple

with open("test.csv", "r") as csvfile:
    csv_reader = csv.reader(csvfile)
    csv_writer = csv.writer(open("outfile.csv","w", newline=""))
    head = next(csv_reader)   ## read header
    csv_writer.writerow(head ["ranged"])  ##write header to out file
    for row in csv_reader:    ## iterate over other rows
        toExpand = row[COL_TO_EXPAND]
        if "(" not in toExpand:
            csv_writer.writerow(row [toExpand])
            break
        fixed = toExpand[:toExpand.index("(")]  ## extract fixed part
        varying = toExpand[len(fixed) 1:-1].split("-")  
        allVars = getAllVars(varying)  ## expand variable part
        for e in allVars:  ## iterate over the expanded range
            newRow = row [fixed e]  ## (why?)
            csv_writer.writerow(newRow) ## print it to out file


You can just put all pieces together and it works.

PS D:\my_projects\DemoProject> type .\test.csv   
id,name,range,status
1,paul,1234(0-2),failed
2,jerom,4321(000-002),passed
3,nanad,54(10-13),failed

PS D:\my_projects\DemoProject> type .\outfile.csv
id,name,range,status,ranged
1,paul,1234(0-2),failed,12340
1,paul,1234(0-2),failed,12341
1,paul,1234(0-2),failed,12342
2,jerom,4321(000-002),passed,4321000
2,jerom,4321(000-002),passed,4321001
2,jerom,4321(000-002),passed,4321002
3,nanad,54(10-13),failed,5410
3,nanad,54(10-13),failed,5411
3,nanad,54(10-13),failed,5412
3,nanad,54(10-13),failed,5413
PS D:\my_projects\DemoProject>
  • Related