Ha Hacker Ha Hacker - 1 month ago 11
Python Question

Removing first line of Big CSV file?

How should I remove the first line of a big CSV file in python?
I looked into the previous solutions in here, one was:

with open("test.csv",'r') as f:
with open("updated_test.csv",'w') as f1:
f.next() # skip header line
for line in f:
f1.write(line)


which gave me this error:

f.next() # skip header line
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'


the other solution was:

with open('file.txt', 'r') as fin:
data = fin.read().splitlines(True)
with open('file.txt', 'w') as fout:
fout.writelines(data[1:])


Which brings memory issue!

Answer

Replace f.next() to next(f)

with open("test.csv",'r') as f, open("updated_test.csv",'w') as f1:
    next(f) # skip header line
    for line in f:
        f1.write(line)