所以我试图跳过.txt文件中的几行,然后使用csv reader创建一个CSV文件。需要跳过18行。这可以完成工作,但我很确定有一种简单的方法可以跳过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)
这对我有用,但我如何将代码清理为更简单的版本。谢谢!
答案 0 :(得分:3)
使用range
:
main.py
答案 1 :(得分:1)
for i in range(18):
next(cr)
使用for
循环。或者您可以使用itertools.dropwhile
for line in (r[:20] for i, r in itertools.dropwhile(lambda x: x[1] < 18 , enumerate(cr))):
答案 2 :(得分:1)
你在下面使用了for循环,这很奇怪,但是没有考虑到同样的问题。
您的代码很容易被这样的代码替换
for i in range(18):
next(cr)
writer.writerow(next(cr))
这将调用next(cr)18次,然后调用writer.writerow
答案 3 :(得分:1)
这个怎么样,
java.lang.ClassCastException: org.apache.geronimo.mail.handlers.HttpHandler cannot be cast to javax.activation.DataContentHandler jax rs
如@PatrickHaugh所述,上述解决方案对大文件无效。以下是大文件的解决方案。
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