Search code examples
pythonarraysstringcsvzip

adding extra row to text file in python


I have a code that is something like that:

x = zip(sources,clist,RMSlist,residuelist)
name1 = string("sources")
name2 = string("clist")
name3 = string("RMSlist")
name4 = string("residuelist")
y = zip(name1,name2,name3,name4)
with open('test.csv', 'w') as f:
  writer = csv.writer(f, delimiter='\t')
  writer.writerows(y) 
  writer.writerows(x)   

My goal is to write each array in a column, but i want above that column a definition (a name) for it. Which was my attempt with the 4 names defined.

It Just for the sake of understanding the text file output better


Solution

  • I think your problem is because you use zip() and writerows with char s at the end.

    You should create normal list with names

    names = ["sources", "clist", "RMSlist", "residuelist"]
    

    and use writerow (without char s at the end) to write single row

    writer.writerow(names)  # without char `s`
    

    BTW: Instead of name names (which may means many objects) you can use name header which means single object.


    header = ["sources", "clist", "RMSlist", "residuelist"]
    
    rows = zip(sources, clist, RMSlist, residuelist)
    
    with open('test.csv', 'w') as f:
      writer = csv.writer(f, delimiter='\t')
      writer.writerow(header)  # without char `s` to write one row
      writer.writerows(rows)   # with char `s` to write many rows