Replace data in csv file using python

后端 未结 2 1568
傲寒
傲寒 2020-12-18 15:29

This is the new input file format. I need to automate the process of replacing the content of one column in a .csv file with the use of python. I can also open the .csv file

2条回答
  •  抹茶落季
    2020-12-18 16:00

    Read the .csv line-by-line, split on ,, and replace the second column with "input". Write it out (to a different file) as you go:

    f = open('mycsv.csv','rb')
    fo = open('out.csv','wb')
    
    # go through each line of the file
    for line in f:
        bits = line.split(',')
        # change second column
        bits[1] = '"input"'
        # join it back together and write it out
        fo.write( ','.join(bits) )
    
    f.close()
    fo.close()
    

    Then you can rename it to replace the original file if you like.

提交回复
热议问题