Search code examples
pythonpython-3.xcsvpython-watchdog

how do add serial numbers to a csv everytime something is appended?


I've built a file monitoring app using watchdog for new file additions. it appends some data about evey new file that's added to a csv in parent directory. I now also want to append serial numbers along with the data. how do i go about doing this?

here's what i now have:

with open("some_csv.csv", 'a', newline='') as fd:
    # i want to append auto incrementing serial numbers here
    fd.write(file_name)
    fd.write(file_size)
    fd.write(file_creation)
    fd.write(number_columns)

Solution

  • If you are OK with pandas module, it is very easy.

    import pandas as pd
    df = pd.read_csv('test2.csv', sep=',', header=None)
    df.to_csv('test3.csv', index_label='index')
    

    The above code will generage a csv named 'tes3.csv' with an auto incrementing column named 'index'