mardi 20 juin 2017

Append A Random Number in every line in CSV file python

I'm trying to append a random number in every line in csv file in row[2] i get the information from the original file then i write it to a new csv file + i append the second row with the random number but i get the same random number in every line when i run the script ( i have the read file which contain exp:

car,golf

when i write this data to new csv file and append the second row i get the same number for every line

car,golf,1777
car,bmw,1777
car,m3,1777

how can i fix this so i can have random number in every line

data = []  
    with open("read.csv", "r") as the_file:
        sid_row = 5000
        for i in range(sid_row):
            line = str(random.randint(1,5000))
            sid = line
        reader = csv.reader(the_file, delimiter=",")
        for row in reader:
            try:
                new_row = [row[0], row[1],sid]
                data.append(new_row)
            except IndexError as error:
                print(error)
                pass
    with open("Random.csv", "w+") as Ran_file:
        writer = csv.writer(Ran_file, delimiter=",")
        for new_row in data:
            writer.writerow(new_row)




Aucun commentaire:

Enregistrer un commentaire