简体   繁体   English

读取每隔一行并打印到新文件

[英]Read every second line and print to new file

I am trying to read every second line in a CSV file and print it in a new file. 我试图读取CSV文件中的每一行,并将其打印在一个新文件中。 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. 我正在使用的代码只是通过查看n的modolus值来确定它是否实际上每隔一行。 I have even tried with strip() and rstrip() which still takes the blank lines. 我甚至尝试使用strip()rstrip() ,它仍然采用空白行。

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会自动输出一个新行,或者使用sys.stdout.write或者使用尾随逗号来抑制换行符,例如:

print >> file, line,

Anyway, the better way to approach this overall is to use itertools.islice for: 无论如何,更好的方法是使用itertools.islice

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. 试着看看python库中的csv文件。 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): ... for(line_index,line)枚举(行):...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM