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.
A recommendation: to clean up your code a bit, and get rid of the need to manually increment and declare a counter variable, use:
for (line_index, line) in enumerate(lines): ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.