2

I want to delete only the first row (not the headers) of a CSV using Python.

I have tried many solutions using the csv module or pandas but nothing have worked for me yet. All the solutions either printed out the csv and didn't modify the original file.

And importantly, I do not want to print out or skip/ignore the first line, I want to delete it and save it to the original file, not creating another file.

2
  • Read the entire CSV into a Pandas dataframe, remove the first row of the dataframe, save the entire resulting dataframe to a CSV file with the same name as in your input file. Commented Jun 18, 2022 at 8:58
  • 1
    df = pd.read_csv(...,skiprows=1) ; df.to_csv('new_file.csv',index=False) ? Commented Jun 18, 2022 at 10:37

4 Answers 4

3
FILENAME = 'test.csv'
DELETE_LINE_NUMBER = 1

with open(FILENAME) as f:
    data = f.read().splitlines() # Read csv file
with open(FILENAME, 'w') as g:
    g.write('\n'.join([data[:DELETE_LINE_NUMBER]] + data[DELETE_LINE_NUMBER+1:])) # Write to file

Original test.csv:

ID, Name
0, ABC
1, DEF
2, GHI
3, JKL
4, MNO

After run:

ID, Name
1, DEF
2, GHI
3, JKL
4, MNO

(deleted 0, ABC)

Sign up to request clarification or add additional context in comments.

3 Comments

Just added a DELETE_LINE_NUMBER constant so you can choose which line you want to delete (0 = headers, 1 = first row, etc.)
OP didn’t say what their CSV looks like, but this won’t work if the first line has line breaks as part of the data. I always recommend using Python’s CSV module to be fully compliant and safe when reading/writing CSV files.
Yeah, they didn't put it in the question, but they did comment i havent put my example csv in the question but you actually used similar example csv as mine so I think this is ok
2

After reading the csv file as csv reader, next() will return each row in the file, so can be solved like this:

import csv
csv_file_name= '<your_file_name>.csv'

file = open(csv_file_name)
csvreader = csv.reader(file)

# store headers and rows
header = next(csvreader)

# ignore first row 
next(csvreader)

# store other rows
rows = []
for row in csvreader:
        rows.append(row)

file.close()

with open(csv_file_name, 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write multiple rows
    writer.writerows(rows)

1 Comment

How would OP skip the first row, like they asked for? (Best answer so far, using CSV and next()… just need to get that requirement in).
1

If your (CSV) file is small enough, read it into memory, remove the line and write it back.

No Pandas or even the csv module needed here.

# Read lines into list
with open("myfile.csv") as f:
    lines = list(f)

lines.pop(1)  # pop the second line out (assuming the zeroth line is headers)

# Write lines back into file
with open("myfile.csv", "w") as f:
    for line in lines:
        f.write(line)

If your file is larger, don't read it all into memory, but filter it into a second file on the fly, then replace the first:

import os

with open("myfile.csv") as rf, open("myfile.csv.temp", "w") as wf:
    for i, line in enumerate(rf):
        if i != 1:  # Everything but the second line
            wf.write(line)

os.replace("myfile.csv.temp", "myfile.csv")

1 Comment

Using the CSV module for reading/writing CSV files is always better, safer, and more compliant than not. Why recommend avoiding an actual parser for a formally specified format? What’s to be gained by essentially writing an ad-hoc CSV parser?
0

You can try that. It works if the file isn't too big

# Read the data
with open("your file.csv", "r") as f:
    data = f.read().split("\n")

# Remove the 1st line
del data[1]

# Save the data
with open("your file.csv", "w") as f:
    f.write("\n".join(data))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.