简体   繁体   English

在Python中跳过多行

[英]Skip multiple rows in Python

so I'm trying to skip over several rows from a .txt file and then creating a CSV file using csv reader. 因此,我尝试跳过.txt文件中的几行,然后使用csv阅读器创建CSV文件。 18 rows need to be skipped. 需要跳过18行。 This gets the job done but I'm pretty sure there is an easy way of skipping 18 rows instead of using next() 18 times. 这可以完成工作,但是我敢肯定,有一种跳过18行而不是使用next()18次的简单方法。

import csv
import os

my_file_name = os.path.abspath('LensBank.txt')
cleaned_file = "LensBankClean.csv"
with open(my_file_name, 'r', newline='') as infile, open(cleaned_file, 'w',newline='') as outfile:
    writer = csv.writer(outfile)
    cr =  csv.reader(infile, delimiter=',')

    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    next(cr)
    writer.writerow(next(cr))

    for line in (r[:20] for r in cr):
     writer.writerow(line)

This works for me but how would I clean up the code to a much simpler version. 这对我有用,但是我如何将代码清理为更简单的版本。 Thanks! 谢谢!

Use range : 使用range

for skip in range(18):
    next(cr)
for i in range(18):
    next(cr)

Use a for loop. 使用for循环。 Or you can use itertools.dropwhile 或者您可以使用itertools.dropwhile

for line in (r[:20] for i, r in itertools.dropwhile(lambda x: x[1] < 18 , enumerate(cr))):

That's strange that you used a for loop below, but haven't considered it for the same problem. 奇怪的是,您在下面使用了for循环,但没有针对相同的问题考虑它。

your code can easily be replaced by something like this 您的代码可以很容易地被这样的东西代替

for i in range(18):
    next(cr)
writer.writerow(next(cr))

This will call next(cr) 18 times, and afterwards call writer.writerow 这将调用next(cr)18次,然后调用writer.writerow

How about this, 这个怎么样,

import csv

# read a csv file into a list of lists
with open(in_file, 'r') as f_in:
    lists = [row for row in csv.reader(f_in, delimiter=',')] 

# write a list of lists to a csv file
with open(out_file, 'w') as f_out:
    writer = csv.writer(f_out)
    writer.writerows(lists[18:])    # skip the first 18 lines

As mentioned by @PatrickHaugh, the above solution is not effective for a large file. 如@PatrickHaugh所述,以上解决方案对于大文件无效。 Below is the solution for a big files. 以下是大文件的解决方案。

with open(in_file,'r') as f_in, open(out_file,'w') as f_out:
    # skip the first n lines
    for _ in range(18):
        next(f_in)
    for line in f_in:
        f_out.write(line)

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

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