I am trying to read every second line in a CSV file and print it in a new file. Unfortunately i am getting a blank line which i am unable to remove.
lines = open( 'old.csv', "r" ).readlines()[::2]
file = open('new.csv', "w")
n = 0
for line in lines:
n += 1
if ((n % 2) == 1):
print >> file, line
The code i am using is simply by looking at the modolus value of n
to decide if its actually every second line or not. I have even tried with strip()
and rstrip()
which still takes the blank lines.
In answer to your question, your blank line is coming from:
print >> file, line
Using print
like that automatically outputs a new line, either use sys.stdout.write
or, use a trailing comma to suppress the newline character, eg:
print >> file, line,
Anyway, the better way to approach this overall is to use itertools.islice
for:
from itertools import islice
with open('input') as fin, open('output', 'w') as fout:
fout.writelines(islice(fin, None, None, 2))
And if necessary, filter out the blank lines first, then take every 2nd from that...
non_blanks = (line for line in fin if line.strip())
fout.writelines(islice(non_blanks, None, None, 2))
Much more convenient and flexible than mucking about with modulus and such.
Try taking a look at the python library for csv files. It is pretty comprehensive and should help you do what you are looking to do more cleanly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With