-2

I have a CSV file that has about 20 columns and 50 rows. I am trying to overwrite the first row so I can change the labels for the columns. I tried to simply open the writer and write on the file from scratch, but it cleared the whole file under the first column then.

Any ideas would be very much appreciated!

martineau
  • 119,623
  • 25
  • 170
  • 301
  • can you post a sample of the data. Why is deleting the first row necessary for you to change the labels for the column? It would help if you post what you attempted; from where are the new labels for the columns going to come from? – Nie Selam Jan 04 '18 at 00:20
  • Just skip the header from the file (with `next` or some sort of logic) and insert the replacement text in the stream. – dawg Jan 04 '18 at 01:45

2 Answers2

0

Since you have a small table, you should just read the entire file into memory using the csv library in Python, change the first line and then write the entire file back into csv.

This question is similar to the one noted below, which outlines this approach more completely.

Change specific value in CSV file via Python

Haziq Nordin
  • 195
  • 1
  • 3
  • 10
0

It's hard to tell without seeing the file or your code but you could use Pandas read_csv. In Pandas there is a skiprows argument so you could do something like

import pandas as pd df = pd.read_csv(fl_name,skiprows=list(range(1)), delimiter='\t')

If you only need certain columns you can also use the usecols command to only read in the columns you're interested in. Hope this helps.

Hawky
  • 85
  • 1
  • 6