使用Python编辑csv文件时跳过标题我使用下面引用的代码使用Python编辑csv。代码中调用的函数形式代码的上半部分。问题:我希望下面引用的代码从第2行开始编辑csv,我希望它排除包含标题的第1行。现在它只在第一行应用函数,我的标题行正在改变。in_file = open("tmob_notcleaned.csv", "rb")reader = csv.reader(in_file)out_file = open("tmob_cleaned.csv", "wb")writer = csv.writer(out_file)row = 1for row in reader:
row[13] = handle_color(row[10])[1].replace(" - ","").strip()
row[10] = handle_color(row[10])[0].replace("-","").replace("(","").replace(")","").strip()
row[14] = handle_gb(row[10])[1].replace("-","").replace(" ","").replace("GB","").strip()
row[10] = handle_gb(row[10])[0].strip()
row[9] = handle_oem(row[10])[1].replace("Blackberry","RIM").replace("TMobile","T-Mobile").strip()
row[15] = handle_addon(row[10])[1].strip()
row[10] = handle_addon(row[10])[0].replace(" by","").replace("FREE","").strip()
writer.writerow(row)in_file.close() out_file.close()我试图通过初始化row变量来解决这个问题,1但它没有用。请帮我解决这个问题。
3 回答
一只斗牛犬
TA贡献1784条经验 获得超2个赞
您的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)
临摹微笑
TA贡献1982条经验 获得超2个赞
解决此问题的另一种方法是使用DictReader类,该类“跳过”标题行并使用它来允许命名索引。
鉴于“foo.csv”如下:
FirstColumn,SecondColumnasdf,1234qwer,5678
像这样使用DictReader:
import csvwith open('foo.csv') as f: reader = csv.DictReader(f, delimiter=',') for row in reader: print(row['FirstColumn']) # Access by column header instead of column number print(row['SecondColumn'])
添加回答
举报
0/150
提交
取消