使用Python编辑csv文件时跳过标题 [英] Skip the headers when editing a csv file using Python
问题描述
我使用下面引用的代码来使用Python编辑csv。在代码中调用的函数形成代码的上部。
I am using below referred code to edit a csv using Python. Functions called in the code form upper part of the code.
问题:我想要下面引用的代码从第二行开始编辑csv,我想要排除包含标题的第一行。现在它只应用第一行的函数,我的标题行被改变。
Problem: I want the below referred code to start editing the csv from 2nd row, I want it to exclude 1st row which contains headers. Right now it is applying the functions on 1st row only and my header row is getting changed.
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 = 1
for 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
,但是无效。
I tried to solve this problem by initializing row
variable to 1
but it didn't work.
请帮助我解决此问题。
推荐答案
您的
为了让它在你的循环之前跳过一个项目,只需调用next(reader,None)
,并忽略返回值。
To make it skip one item before your loop, simply call next(reader, None)
and ignore the return value.
你也可以简化你的代码;使用打开的文件作为上下文管理器让它们自动关闭:
You can also simplify your code a little; use the opened files as context managers to have them closed automatically:
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()
:
If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next()
to writer.writerow()
:
headers = next(reader, None) # returns the headers or `None` if the input is empty
if headers:
writer.writerow(headers)
这篇关于使用Python编辑csv文件时跳过标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!