Reputation: 35
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.
Upvotes: 2
Views: 14969
Reputation: 69
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)
Upvotes: 2
Reputation: 3624
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
)
Upvotes: 3
Reputation: 190
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))
Upvotes: 0
Reputation: 168834
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")
Upvotes: 1