Read every second line and print a new file

I am trying to read every second line in a CSV file and print it in a new file. Unfortunately, I get an empty string that I cannot delete.

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'm using is just to look at the value of modolus n to decide whether this is every second line or not. I even tried with strip() and rstrip() , which still accepts empty lines.

+6
source share
3 answers

In answer to your question, your empty line comes from:

 print >> file, line 

Using print , which automatically prints a newline, use sys.stdout.write or use a sys.stdout.write comma to suppress the newline character, for example:

 print >> file, line, 

In any case, the best 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 the empty lines first, and then take every second of this ...

 non_blanks = (line for line in fin if line.strip()) fout.writelines(islice(non_blanks, None, None, 2)) 

It is much more convenient and flexible than thinning with a module, etc.

+11
source

Try a look at the python library for csv files. It is quite comprehensive and should help you do what you want to do more cleanly.

+1
source

Recommendation: clear your code a bit and get rid of the need to increment manually and declare a counter variable, use:

for (line_index, line) in the enumeration (line): ...

+1
source

Source: https://habr.com/ru/post/948820/


All Articles