Add row numbers to CSV

Question:

Say I have this CSV:

apple
orange
banana
strawberry

How could I make it so that there’s always the correct line number to the left of the item and adapt it in the case an item is added or removed from the csv.

Ex:

1,apple
2,orange
3,banana
4,strawberry

If I remove banana –> strawberry becomes line #3

1,apple
2,orange
3,strawberry

Then if I add banana:

1,apple
2,orange
3,strawberry
4,banana

I’m thinking of doing an independent function that initiates at the very end of when the CSV is done being edited. It’ll check the file and arrange it on its own after all modifications have been made to the CSV.

Asked By: Trigon

||

Answers:

import pandas as pd
df = pd.read_csv('XYZ.csv')
df['row_num'] = df.reset_index().index
#df.to_csv("XYZ_new.csv")
print(df)

let me know if it helps

Answered By: Rahul Vaidya

You can use enumerate. By default it start with 0.

Code (Python3)

    csv_data = {
        'apple',
        'orange',
        'banana',
        'strawberry'
    }
    
    for index, key in enumerate(csv_data, start=1):
        # save to csv file
        print('{}t{}'.format(index, key))
    
    # remove 'banana'
    print("nremove 'banana'")
    new_csv_data = {key for index, key in enumerate(csv_data) if key != 'banana'}
    
    for index, val in enumerate(new_csv_data, start=1):
        # save to csv file
        print('{}t{}'.format(index, val))
    
    # add 'banana'
    print("nadd 'banana'")
    new_csv_data.add('banana')
   
    for index, val in enumerate(new_csv_data, start=1):
        # save to csv file
        print('{}t{}'.format(index, val))

Output

1 orange
2 strawberry
3 apple
4 banana

remove ‘banana’
1 orange
2 strawberry
3 apple

add ‘banana’
1 orange
2 strawberry
3 apple
4 banana

Answered By: sambabug
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.