0

Can someone give me the best way to skip the first 2 lines in the CSV file. I am trying to find and replace values inside the CSV file using the code, but I'd like it to ignore the first two rows and start from the 3rd one.

Thank you!

import csv

reps = {
    '+' : 'Positive',
    '++' : 'Strong Positive',
    '-' : 'Negative',
    '+/-' : 'Resonable'}

def replace_all(text, dic):
    for i, j in reps.items():
        text = text.replace(i, j)
    return text

with open('apitest.csv','r') as f:
    text=f.read()
    text=replace_all(text,reps)

with open('apitest.csv','w') as w:
    w.write(text)
  • 4
    Why are you importing the `csv` module then ignoring it? Did you see [Skip the headers when editing a csv file using Python](http://stackoverflow.com/q/14257373)? Skipping two rows is then as easy as using `next()` twice, or you can use `next(itertools.islice(reader, 2, 2), None)` to ignore 2 rows with one command. – Martijn Pieters Feb 18 '15 at 20:30
  • Thanks, I'm going to try that, I get confused quite easily about where to place and enter the code. – Hassan7863 Feb 18 '15 at 20:36
  • I tried that, but the data inside the CSV file gets deleted and there is nothing left in there – Hassan7863 Feb 18 '15 at 20:41
  • Sounds like you are writing back an empty list then.. – Martijn Pieters Feb 18 '15 at 21:05

1 Answers1

0

Your current code is reading the entire file as a single thing, passing that single thing to replace_all, and then writing the returned single thing back to the original file (which is a huge mistake -- don't ever use the same filename for the output without at least making a copy of it somewhere).

Some ideas:

  • text = f.readlines()
  • text = f.read(); text = text.split('\n')

then

new_text = []
for line in text:
  new_text.append(replace_all(line))
...
w.write('\n'.join(new_text))

A few pieces are still missing, but that should get you going.

Ethan Furman
  • 63,992
  • 20
  • 159
  • 237