您的
reader变量是可迭代的,通过循环它可以检索行。
要使其在循环前跳过一项,只需调用
next(reader,None)并忽略返回值即可。
您还可以稍微简化代码;将打开的文件用作上下文管理器以使其自动关闭:
with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile: reader = csv.reader(infile) next(reader, None) # skip the headers writer = csv.writer(outfile) for row in reader: # process each row writer.writerow(row)# no need to close, the files are closed automatically when you get to this point.如果您想将标头写入未经处理的输出文件中,也很容易,请将输出传递
next()给
writer.writerow():
headers = next(reader, None) # returns the headers or `None` if the input is emptyif headers: writer.writerow(headers)



