Home > OS >  How to delete first row in a csv file using python
How to delete first row in a csv file using python

Time:06-18

i want to delete only first row (not the headers) of the csv in python I have tried many solutions with import csv or pandas but nothing have worked for me yet. all solutions either printed out the csv and didnt modify the original file.

And important 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.

Thank you:)

CodePudding user response:

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)

CodePudding user response:

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")

CodePudding user response:

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))

CodePudding user response:

Just store the header names in a list, Then the CSV rows in a list of lists, where each list is a row value. Then you can just write these values in a CSV file with the same file name.


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)
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)
  • Related