因此我試圖跳過.txt文件中的多行,然後使用csv閱讀器創建CSV文件。 18行需要跳過。這可以完成工作,但我確信有一個簡單的方法可以跳過18行而不是使用next()18次。在Python中跳過多行
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)
這適用於我,但我怎麼會清理代碼到一個更簡單的版本。謝謝!
...它可以在'infile'上完成,然後創建'csv.reader'來保存幾個cpu週期。 – tdelaney