Adding the header to a csv file

后端 未结 4 1217
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 20:21

I have a csv file with the dimensions 100*512 , I want to process it further in spark. The problem with the file is that it doesn\'t contain header i.e

4条回答
  •  抹茶落季
    2021-01-26 20:27

    Bit a old way ...

    Content of demo.csv before columns:

    4444,Drowsy,bit drowsy
    45888,Blurred see - hazy,little seeing vision
    45933,Excessive upper pain,pain problems
    112397013,air,agony
    76948002,pain,agony
    

    Content of xyz.txt :

    Col 1,Col 2,Col 3
    

    Code with comments inline

    #Open CSV file
    with open("demo.csv", "r+") as f:
        #Open file which has header
        with open("xyz.txt",'r') as fh:
            #Read header
            header = fh.read()
            #Read complete data of CSV file
            old = f.read()
            #Get cursor to start of file
            f.seek(0)
            #Write header and old data to file.
            f.write(header+ "\n" + old)
    

    Content of demo.csv:

    Col 1,Col 2,Col 3
    4444,Drowsy,bit drowsy
    45888,Blurred see - hazy,little seeing vision
    45933,Excessive upper pain,pain problems
    112397013,air,agony
    76948002,pain,agony
    

提交回复
热议问题